Welcome to Lesson 8!

Learning Objectives
By the end of today's class, you should know...
  • How do you compare chars and use them in the test condition of an if statement?
  • How do you compare Strings and use them in the test condition of an if statement?
  • How to make decisions when there are multiple alternatives?
  • When does order matter when making decisions?


Announcements
  • Midterm 1 - one week from today
    • Study over your old quizzes, in-class activities and homework
    • Material through if statements (Lesson 2 - Lesson 8)
    • Practice Midterm Questions
  • Don't forget to complete Lab 4 on CodeLab and Quiz 4 by tomorrow night!
  • Note: the homework for tonight may be adjusted according to how far we get today in class


Review Activity

With a partner, answer the following questions:
  • Write one line of code to declare a String variable (name of your choice) and assign it the value $.
  • Write one line of code to declare a char variable (name of your choice) and assign it the value of $.
  • Write a System.out.println statement to print the following message to the console:  Sure! I'll do it. <tab> I "love" boring, repetitive tasks!
  • Write an if statement to check if the the length of a String called name is equal to 0.
    • If so, print out an error message that says "Your name cannot be 0 characters long!"
  • With a partner, identify and correct the 2 mistakes in the code below:

    int guess;
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a guess: ");
    guess = input.nextInt();
    if (guess = 7) {
          System.out.println(“Correct!”);
    } else (guess != 7) {
         System.out.println(“Incorrect!”);
    }


Comparing Characters and Strings

  • Character data can be evaluated using the relational operators as well.
  • Because characters are primitive types, we can use the 6 relational operators (==, !=, <, >, <=, >=) to compare them.
  • Comparing characters works because Java stores characters as numbers using their Unicode values.
Unicode table

  • Note that letters nearer to the start of the alphabet have lower numerical Unicode values.
  • Thus a numerical comparison can decide the alphabetical order of characters.

Example Program Comparing Characters

1
2
3
4
5
6
7
8
9

public static void main(String[] args) {
    
    System.out.println("'A' < 'B': " + ('A' < 'B')); System.out.println("'A' > 'B': " + ('A' > 'B')); System.out.println("'A' <= 'Z': " + ('A' <= 'Z')); System.out.println("'X' >= 'Y': " + ('X' >= 'Y')); System.out.println("'X' == 'X': " + ('X' == 'X')); System.out.println("'X' != 'X': " + ('X' != 'X')); }

Comparing Strings - Equals and EqualsIgnoreCase Methods

  • Strings are not primitive types.
  • Therefore, we must use special String methods to compare them.
  • We have already seen one String method for comparison: equals

System.out.println("car".equals("cat")); //prints false

  • Another useful and related String method is equalsIgnoreCase

System.out.println("car".equalsIgnoreCase("CAR")); //prints true


Comparing Strings - CompareTo and CompareToIgnoreCase Methods

  • To compare Strings alphabetically, Java provides two methods: compareTo and compareToIgnoreCase
  • These methods both return a numerical value to indicate which string came first alphabetically.
    • the first string is comes first alphabetically -> negative number as result
    • the strings are equal -> result of 0
    • the second string comes first alphabetically -> positive number as result
  • For example, imagine that we wish to compare "car" and "cat"
  • Alphabetically, "car" comes before "cat":
    c a r
    c a t
  • If we use the compareTo method on these two strings, we will get the following result:

//"car" comes BEFORE "cat":

System.out.println("car".compareTo("cat")); //negative number

  • Also, alphabetically, "car" comes before "card"
    c a r
    c a r d

//"card" comes AFTER "car":

System.out.println("card".compareTo("car")); //positive number

  • CompareToIgnoreCase works the same way, except it ignores upper and lower case characters.
//"Car" comes BEFORE "car":
System.out.println("Car".compareTo("car")); // negative number

//Ignoring case, "Car" and "car" are equal
System.out.println("Car".compareToIgnoreCase("car")); // 0

Table Summarizing compareTo Method

 Alphabetical Order
 Example Result
 First String comes BEFORE second String
 "cat".compareTo("dog"); Negative Number
 Two Strings are EQUAL
 "cat".compareTo("cat");
 0
 First String comes AFTER second String
"dog".compareTo("cat");
Positive Number

Where Do the Numbers Come From?

  • According to Oracle's String API, the numerical value generated by compareTo is the difference in unicode values between the first differing characters in the two Strings.

Example Program Comparing Strings



public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String s1, s2;
    
    System.out.print("Enter two strings: "); s1 = input.next();
    s2 = input.next();
if (s1.compareTo(s2) < 0)
        System.out.println(s1 + " comes before " + s2);
    else
        System.out.println(s2 + " comes before " + s1 + " or is equals to " + s1);
    input.close();
}

Activity 8.1: Let's Alphabetize! (10 pts)

  • Open up Eclipse and create a new Java project called Alphabetize, with a new class called Alphabetize.java
  • Our program will take in two String inputs from the user, compare then and the output the two Strings in alphabetical order.
  • At the top of your program, declare a string variables called word1.
String word1;
  • Now declare a second String variable called word2.
  • Next, write a System.out.println statement welcoming your user to the program and letting them know that this program will alphabetize two words.
System.out.println("Welcome! Give me two words...\nand I will return them to you in alphabetical order!\n");
  • Run your program to make sure it is giving you the output you expected.
  • Let's prompt the user for the first word and store the result as word1.
System.out.print("Please enter the first word: ");
word1 = input.next(); //assumes new Scanner declared at top of program

  • Do the same for the second word.
  • Now, let's create an if-else statement to determine the ordering of the two words. And, then output the result to our user. The if-else statement will need to use String comparison as discussed above.
  • The code that you have written could be a useful part of a larger program. 
  • Both partners should submit to Canvas when finished.


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! ***"); }
    
input.close();
}

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 8.2: 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. In other words: you will need to add in else if statements, 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


Wrap up

  • Answer the questions from today's learning objectives

Upcoming Assignments

~Have a Great Weekend!~