Welcome to Lesson 9!

Learning Objectives
By the end of today's class, you should know...
  • How to make decisions when there are multiple alternatives?
  • When does order matter when making decisions?
  • How do you format decimal numbers for printing
  • What is a final and how do you declare one?
  • What is are magic numbers and why should they be avoided?
  • What are the short cut assignment operators for add, subtract, multiply, divide, and modulus?
  • What are the increment and decrement operators?
    • What is the difference between pre and post increment and decrement?
  • What is casting?
    • How do you cast an integer to a double and a double to an integer?


Announcements

  • Midterm 1 next class (Lesson 2 - Lesson 8)
    • Study over review activities and quizzes
    • Study over programs you have written for homework
    • If there was a homework assignment you struggled with, get help before the midterm!
  • Return Quiz 3
  • Assignment 9 to be due on Thursday due to midterm.
  • Don't forget Lab 5 due tomorrow!


Review Activity:
With a partner, answer the following questions:

  • What will the following program print to the console?

String studentName1 = "Herman";

String studentName2 = "Hank";

if (studentName1.compareTo(studentName2) < 0) {

    System.out.println("Alpha");

} else {

    System.out.println("Beta");

}


  • With a partner, correct the mistakes below

a.

String name = Jane;


if (name = “Jane”) {

    System.out.println("Hi, Jane!");

} else (name != “Jane”) {

    System.out.println(“Hi, Not Jane!”);

}

b.

char = a;



Making Decisions Continued

"Nesting" if Statements
  • The inner if statement is evaluated only if the test condition of the outer if test first evaluates to true
  • The following code shows an example of a nested if statement

Example Showing a Nested if Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args) {

    int guess = 0; Scanner input = new Scanner(System.in);

    System.out.println("I'm thinking of a number between 1 and 10.");
    System.out.println("Can you guess it?\n");
    
    System.out.print("Enter your guess: "); guess = input.nextInt(); if (guess != 7) { if (guess < 7) { System.out.println("Your guess is too low."); } else { System.out.println("Your guess is too high."); } } else { System.out.println("*** Correct! ***"); } }

Nesting in the else Clause

  • You can also nest if statements in the else clause
  • When used this way, the computer can make only one selection
  • As soon as a condition is found to be true, the rest of the selections are ignored
  • The following code shows an example of a nested else if statement
  • For example:
    if (guess < 7)
    {
        System.out.println("Your guess is too low.");
    }
    else if (guess > 7)
    {
        System.out.println("Your guess is too high.");
    }
    else
    {
        System.out.println("*** Correct! ***");
    }
    
  • The trick in understanding this type of logic is to remember:
    • You start at the top
    • The computer makes only one selection
    • Once the selection is made and processes, the computer skips the rest of the options


Example Showing a Nested if else Statement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void main(String[] args) {

    int guess = 0; Scanner input = new Scanner(System.in);

    System.out.println("I'm thinking of a number between 1 and 10.");
    System.out.println("Can you guess it?\n");
    
    System.out.print("Enter your guess: "); guess = input.nextInt(); if (guess < 7) {     System.out.println("Your guess is too low.");

   } else if (guess > 7) { System.out.println("Your guess is too high."); } else { System.out.println("*** Correct! ***"); } }


Programming Style: Indentation of if-else-if Statements

  • Note the alignment of the nested statements below:
  • Each statement inside of the if, else if or else clauses need to be indented.
    if (guess < 7)
    {
        System.out.println("Your guess is too low.");
    }
    else if (guess > 7)
    {
        System.out.println("Your guess is too high.");
    }
    else
    {
        System.out.println("*** Correct! ***");
    }
    
  • This shows more clearly that we are making a single choice among multiple alternatives
  • Also, it prevents indentations from cascading to the right as we add more selections

Multiple Alternatives

  • By using collections of if-else statements, a program can distinguish between multiple alternatives

Choosing Between Alternatives

  • This program has five alternatives to choose from:
    1. "penny"
    2. "nickel"
    3. "dime"
    4. "quarter"
    5. erroneous input
  • Note that the order that the alternatives are checked is unimportant
  • We can follow the alternatives in the flowchart shown below

Flowchart of Multiple Alternative for Converting Coins to Values

Flow chart of coin program using else if

  • For example, consider the following example where a user enters the name of a coin, and the program displays the value:

    Program Converting Coin Names to Values

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

     
    System.out.print("Enter coin name: "); String name = input.next();
    double value = 0; if (name.equals("penny")) { value = 0.01; } else if (name.equals("nickel")) { value = 0.05; } else if (name.equals("dime")) { value = 0.10; } else if (name.equals("quarter")) { value = 0.25; } else { System.out.println(name + " is not a valid coin name"); }

      System.out.println("Value = " + value); }

Activity 9.1: Grades (10 pts)

We want to write a program to calculate a student's letter grade according to the following table:

Numerical GradeLetter Grade
greater than or equal to 90A
less than 90 but greater than or equal to 80B
less than 80 but greater than or equal to 70C
less than 70 but greater than or equal to 60D
less than 60F
  • Find a partner for pair programming.
  • Create a new Java project named Grader with a class Grader.java.
  • Add code to get user input into a variable named score of type double. When you run the program after adding this code, the output should look like:
    Enter a score: 95.7
    

    Make sure you declare the variable with a compatible data type. Note that the underlined numbers above shows what the user enters and is not part of your code

  • First we will look at a series of if statements and see that if statements alone are not enough to solve this problem. Copy the following into your program after the input statements:

String grade="";
if (score >= 90)
{
    grade = "A";
}
if (score >= 80)
{
    grade = "B";
}
if (score >= 70)
{
    grade = "C";
}
if (score >= 60)
{
    grade = "D";
}
if (score < 60)
{
    grade = "F";
}
System.out.println(grade);


  • Compile and run the program and see if you can spot the error that will occur. There is a logic problem with this code. Each test condition needs to work over a range of values rather than with a single value.

  • How can we fix this problem
  • Perhaps the most elegant solution is to nest an if statement in the else clause of the preceding if. Modify the series of if statements to include an else clause as shown below:

         String grade;
    if (score > = 90)
    {
        grade = "A";
    }
    else if (score >= 80)
    {
        grade = "B";
    }
    //you fill in the statements here
    else
    {
        grade = "F";
    }
    System.out.println(grade);


  • We are nesting if statements in the else clause. Nesting in the else clause makes each test condition of the if statement exclusive of the others, because each test condition eliminates all the preceding conditions.
  • Compile and run your modified program to make sure you made the changes correctly. When you run the program, the output should look like:
    Enter a score: 80
    B
    

    Run your program a few times with different score to verify that any score displays the correct letter grade.

  • When finished, both partners should upload Grader.java to Canvas.


Importance of Using if-else-if Structure

  • Note that we cannot remove the else portion of the structure like shown below:

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a magnitude on the Richter scale: ");
        double richter = input.nextDouble();
       
        if (richter >= 8.0) { // Does not use else
            System.out.println("Most structures fall");
        }
        if (richter >= 7.0) {
            System.out.println("Many buildings destroyed");
        }
        if (richter >= 6.0) {
            System.out.println("Many buildings considerably damaged, some collapse");
        }
        if (richter >= 4.5) {
            System.out.println("Damage to poorly constructed buildings");
        }
        if (richter >= 3.5) {
            System.out.println("Felt by many people, no destruction");
        }
        if (richter >= 0) {
            System.out.println("Generally not felt by people");
        }
        if (richter < 0) {
            System.out.println("Negative numbers are not valid");
        }

  • The conditions must be exclusive and we need the else-if conditions to ensure exclusivity
  • Independent if statements may cause a single input to print several messages


When Order Matters

  • In some cases, the order of the tests is important
  • For example, look at the following program from displays a description of the likely impact of an earthquake based on its magnitude on the Richter scale

Program Showing Multiple Alternatives Where Order Matters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Enter a magnitude on the Richter scale: "); double richter = input.nextDouble(); if (richter >= 8.0) { System.out.println("Most structures fall"); } else if (richter >= 7.0) { System.out.println("Many buildings destroyed"); } else if (richter >= 6.0) { System.out.println("Many buildings considerably damaged, some collapse"); } else if (richter >= 4.5) { System.out.println("Damage to poorly constructed buildings"); } else if (richter >= 3.5) { System.out.println("Felt by many people, no destruction"); } else if (richter >= 0) { System.out.println("Generally not felt by people"); } else { System.out.println("Negative numbers are not valid"); } }

Order Is Important

  • Note that the order of the tests is important to ensure that the right results are printed
  • If we rearranged the order of the if-else statements, we would get the wrong results
  • For example, if we reversed the order of the tests:
    if (richter >= 0) { // tests in wrong order
        System.out.println("Generally not felt by people");
    } else if (richter >= 3.5) {
        System.out.println("Felt by many people, no destruction");
    } else if (richter >= 4.5) {
        System.out.println("Damage to poorly constructed buildings");
    } else if (richter >= 6.0) {
        System.out.println("Many buildings considerably damaged, some collapse");
    } else if (richter >= 7.0) {
        System.out.println("Many buildings destroyed");
    } else if (richter >= 8.0) {
        System.out.println("Most structures fall");
    } else {
        System.out.println("Negative numbers are not valid");
    }
    
  • This does not work because all values meet the first condition
  • Every other test will never be attempted


Numbers, Formatting and More About Operators

Numbers and Arithmetic

  • Recall that Java uses the following operators for arithmetic:
    • + for addition
    • - for subtraction
    • * for multiplication
    • / for division
    • % for modulus (remainder)
  • The dash is also used for negation (minus sign)
  • We write arithmetic expressions using combinations of numbers, variables and operators
  • For example:
    double area = 0.0, radius = 4.3;
    area = 3.14159 * radius * radius;
    
  • Also recall that the results of integer division are truncated
    7 / 2       // 3
  • We must use modulus operator (%) to get the remainder value
    7 % 2       // 1 (remainder)
  • In addition, we use mathematical functions for more complex operations
    Math.sqrt(3.0 * 3);
  • Java processes arithmetic expressions in the same order (precedence) as algebra:
    1. Parenthesis: ( )
    2. Function calls
    3. Unary operators: +, -
    4. Multiplication, division, modulus: *, /, %
    5. Addition, subtraction: +, -
  • Since parenthesis are processed first, you use parenthesis to change the order of operations

Decimal Formatting

  • Sometimes programs may not display numbers as you would expect!
  • Consider the following program and what it will display:
    public static void main(String[] args) {
        double price = 78.50;
        System.out.println("The price is $" + price);
    }
    
  • We must explicitly tell Java how to output numbers in our programs!
  • These commands do not produce any output but change how System.out outputs floating-point numbers
  • "Magic Formula" to force decimal places:
    System.out.printf("%.2f", value_to_print); 
    
  • % is the place holder representing where you wish to place the value to print inside your message
  • .2f indicates that the floating point value should be printed to 2 decimal places
  • Once we set the decimal formatting, it stays set.
public static void main(String[] args) {

    double price = 78.50;
    System.out.printf("The price is $%.2f", price); }

Final Variables and Magic Numbers

  • A final variable is a variable that cannot change after being assigned a value
  • To declare a constant, we use the keyword: final
    final int my_final = 1;
  • Note that we must assign a value when the final is declared


Magic Numbers

  • Imagine that you are a programmer hired to modify a payroll program
  • You come across the following section of code:
    double pay;
    pay = hours * 7.5 + (hours / 40)
          * (hours - 40) * 7.5 * 0.5;
    
  • The numbers are important to the program, but what do they mean?
  • Numbers like these are called Magic Numbers.
  • They are magic because the value or presence is unexplainable without more knowledge
    • Often, no one knows what they mean after 3 months, including the author
  • A programmer can often infer the meaning of numbers after reading the code carefully
  • A much better coding style is to use named final variables rather than literal numbers
  • For example:
    final double wage = 7.5;
    final double over_time_adder = 0.5;
    final int hours_per_week = 40;
    double pay;
    pay = hours * wage + (hours / hours_per_week)
          * (hours - hours_per_week) * wage * over_time_adder;
    
  • Now it is much easier to understand the code and see any problems or limitations in it
  • Another reason to use named final variables is that it is easier to change the value of the number
  • In the above example, we can easily change the wage without making errors in other parts of our code

More Information


Assignment Operators

  • As we discussed before, we assign values to variables using an equal (=) sign
    int sum = 0;
  • However, the equal sign is really an assignment operator and does not denote equality
  • Thus, unlike math, we can have the same variable on both sides of an equals sign:
    int sum = 25;    // initialize sum to 25
    sum = sum + 10;  // add to sum
    
  • Note that the value of the variable is changed in the second line
  • Reading variables from memory does not change them
  • Values placed into a variable replace (overwrite) previous values:


Shortcut Assignment Operators

  • We can use additional operators to calculate values and assign them to the variable on the left all in one statement
    • Known as shortcut assignment operators
  • The general syntax is:
    variable op= expression;
  • Where op is one of the five arithmetic operators: +-*/%
  • For example, the following two statements create the same result:
    x = x + 3;
    x += 3;
    
  • Shown below are the assignment operators with examples of how they are used:


Summary of Assignment Operators

OperatorDescriptionExampleEquivalent To
=Assigns the value of the expression on the right to the variable on the leftx = 3 
+=Adds the expression on the right to the variable on the leftx += 3x = x + 3
-=Subtracts the expression on the right from the variable on the leftx -= 3x = x - 3
*=Multiplies the expression on the right to the variable on the left and saves the result in the variable on the leftx *= 3x = x * 3
/=Divides the variable on the left by the expression on the right and saves the result in the variable on the leftx /= 3x = x / 3
%=Calculates the remainder from dividing variable on the left by the expression on the right and saves the result in the variable on the leftx %= 3x = x % 3


Increment and Decrement Operators

  • Adding or subtracting one is a common operation in programming
  • Java provides arithmetic shortcuts for these operations with the increment and decrement operators
  • The increment operator (++) adds 1 to a variable's value
  • Pre-increment adds 1 before evaluating an expression
    ++sum;
  • Post-increment evaluates the expression and then adds 1
    sum++;
  • The decrement operator works like the increments operator, except it subtracts 1 from the variable:
    --sum
    sum--
    
  • Pre- and post- increment matters when the operation is part of a larger expression
  • For example, consider the code:
    int x = 5;
    int y = x++;
    System.out.println("x=" + x + " y=" + y);
    
  • We may expect y to be 6 after this code executes
  • Instead, y has the value of 5
  • The reason is that ++ after a variable (post-increment) is equivalent to:
    y = x;
    x = x + 1;
    
  • On the other hand, ++ before a variable (pre-increment) is equivalent to:
    x = x + 1;
    y = x;
    

Casting

  • We often find ourselves converting one data type into another
  • This process is called type conversion or typecasting
  • Java is a strongly-typed language and checks for compatible data types both when compiling and while running
  • To put a value of a different type in a variable, you must convert the type
  • There are two types of conversion: implicit and explicit
  • The term for implicit conversion is sometimes called coercion
  • The most common form of explicit conversion is know as casting

Coercion

  • Type conversion is done automatically (implicitly) when a narrower-type is assigned to a broader-type:
    • Narrower means a smaller number of bytes
    • Broader means a larger number of bytes
  • Data type hierarchy (from narrowest to broadest):
    byte => short => int => long => float => double
                   
    
  • For example:
    double x;
    int n = 5;
    x = n;
    
  • Since n is an integer and x is a double, the value returned by n must be converted to type double before it is assigned to x
  • Note that casting only changes the type of an expression's returned value
    • Not the type of the variable
  • Thus the data type of variable n is unchanged -- it is still an int

Coercion in an Arithmetic Expression

  • Some arithmetic expressions have a mix of data types
  • All values implicitly cast to the highest level before the calculation
  • For example:
    double a;
    int n = 2;
    double y = 1.33;
    a = n / y;
    
  • n is automatically cast to type double before performing the arithmetic

Explicit Casting

  • Explicit casting changes the data type for a single use of the variable
  • To cast, precede the variable name with the new data type in parentheses:
    (typeName) variableName
    
  • Where:
    • typeName: one of the Java data types
    • variableName: the name of the variable
  • For example:
    int n;
    double x = 2.0;
    n = (int) x;
    
  • The value of x is converted from type double to int before assigning the value to n
  • Note that explicit casting is required to assign a broader type to a narrower type
  • ILLEGAL: Implicit casting to a lower data type:
    int n;
    double x = 2.1;
    n = x; // illegal in Java
    

    Illegal since x is double, n is an int, and double is a higher data type than int

  • LEGAL: Explicit casting to a lower data type:
    int n;
    double x = 2.1;
    n = (int) x; // legal in java
    
  • You can use an explicit cast even when an implicit one will be done automatically

Truncation When Casting double to Integer type

  • Converting (casting) a double to integer type does not round -- it truncates
  • The fractional part is lost (discarded, ignored, thrown away)
  • For example:
    int n;
    double x = 3.99999;
    n = (int) x; // x truncated
    
  • Value of n is 3

Activity 9.2: Prices (10pts)

  • Find a partner for pair programming
  • Open up Eclipse, create a new Java project named Price
  • Copy the following program into a class file named Price.java:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    
    
    public static void main(String[] args) {
        String name;
        double price = 0;
      Scanner input = new Scanner(System.in);

    System.out.print("Enter the product name: "); name = input.nextLine();
     
    System.out.print("Price of the " + name + ": "); price = input.nextDouble(); // Insert new statements here System.out.println("Total price: $" + price); }
  • Alter the block comments to include your name and section information to the top of the program.
  • Compile and run the starter program to make sure you entered it correctly.

    When you run the program, the output should look like this:

    Enter the product name: iPod Nano
    Price of the iPod Nano: 149.50
    Total price: $149.5
    

    Note the format of the numbers output for the total price. We will address this formatting issue later in the exercise.

  • Run the program again for a product with a very high cost, like a Boeing 777:
    Enter the product name: Boeing 777
    Price of the Boeing 777: 212345678
    Total price: $2.12345678E8
    

    Note the format of the numbers output for the total price. This format is called exponential notation. You may have encountered it in some of your math classes.

  • Let us correct the formatting of the total price. Alter the System.out statement that prints the total price:
    System.out.printf("Total price: $%.2f\n", price);
    
    Compile and run your program again and verify the output looks like:
    Enter the product name: Boeing 777
    Price of the Boeing 777: 212345678
    Total price: $212345678.00
    
  • Let us add a final variable that we will use later in our program. Enter the following code after the printf statement and before the statement that prints the total price:
    final int percent = 100;
    

    We are declaring this variable rather than using a magic number.

  • Now we will add sales tax to the price of the product. Enter the following code after the percent variable and before the statement that prints the total price:
    double taxRate = 0;
    System.out.print("Enter sales tax rate (%): ");
    taxRate = input.nextDouble();
    double tax = price * taxRate / percent;
    price += tax;
    

    Notice the last statement: price += tax;. This is an alternate way to code the statement: price = price + tax;.

  • Compile and run your modified program and verify the output looks like:
    Enter the product name: iPod nano
    Price of the iPod nano: 89.50
    Enter sales tax rate (%): 9.5
    Total price: $98.00
    
  • Now we will find the whole dollars and cents of the amount to demonstrate casting. Enter the following code after the statement that prints the total price and before the closing curly brace of main:
    int dollars = (int) price;
    System.out.println("In whole dollars: $" + dollars);
    

    Notice the (int) in the first statement. This is known as a type cast or just cast

  • Compile and run your modified program and verify the output looks like:
    Enter the product name: iPod nano
    Price of the iPod nano: 89.50
    Enter sales tax rate (%): 9.5
    Total price: $98.00
    In whole dollars: $98
    



Wrap Up
  • Find a partner and answer the questions from today's learning objectives

Upcoming Assignments

~Have a Great Weekend!~