Welcome to Lesson 7!


Learning Objectives

By the end of today's class, you should know...
  • 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?


1. Lesson 6 Practice Midterm Questions

  • Write a System.out.println statement to print the following message to the console:  "Make"<tab>"Model"<Tab>"Year"<New Line>
  • Given the following lines of code:
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
  • 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!"
  • Identify and correct the 3 mistakes in the code below:

    char choice = 'n';

    if (choice = y) {
          System.out.println(“Yes!”);
    } else (choice != y) {
         System.out.println(“No!”);
    }

2. Strings and If Statements

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

Example Using EqualsIgnoreCase with an if Statement:

Scanner input = new Scanner(System.in);
System.out.print("Do you want to continue? Enter yes/no: ");
String answer = input.next();

if (answer.equalsIgnoreCase("yes")) {
    System.out.println("Program continuing!");
    //rest of program
} else {
    System.out.println("Program ending!");
}


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":
  • 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"

//"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 7.1: Let's Alphabetize! (10 pts)

  • Open up Eclipse and create a new Java project called Activity7, 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. 
  • Submit your program to Canvas when finished.


3. 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); }

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

Activity 7.2: Grades (10 pts)

  • We want to write a program to calculate a student's letter grade according to the following table:
Numerical Grade Letter Grade
greater than or equal to 90 A
less than 90 but greater than or equal to 80 B
less than 80 but greater than or equal to 70 C
less than 70 but greater than or equal to 60 D
less than 60 F

  • Create a new class Grader.java inside of your Activity7 project folder.
  • 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);

  • Here is problem occures.
  • Write a multiline comment above main in which you describe the problem you see and why you think it is happening.
/*
I found this problem:
Reason for this problem:
*/
  • To resolve this problem, convert your second - fourth if statements into 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);


  • Using else if makes each test condition of the if statement exclusive of the others - you tell the computer to find the first correct test condition, and then ignore all the rest of the test 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: 95
    A
    

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

  • When finished, upload Grader.java to Canvas.



Wrap Up
  • What will the following output to the console?
String student1 = "Tanya";
String student2 = "Tasha";

if (student1.compareTo(student2) < 0) {
    System.out.println("Alpha");
} else {
    System.out.println("Beta");
}


Upcoming Assignments

  • Activities 7.1 and 7.2 due Tuesday at 11:59pm
  • Assignment 7 due Friday at 11:59pm
  • Quiz 4 due Friday at 11:59pm

~Have a Great Day!~