Welcome to Lesson 11!

Learning Objectives
By the end of today's class, you should know...
  • What are some pitfalls you might encounter when using logical operators and how can you avoid them
  • What is a switch statement?
  • How does a switch statement compare to an if statement?
  • What is the syntax of a switch statement?
  • What is "fall through"?
  • What is a loop?
  • What is a while loop?
  • What is the syntax of a while loop?
  • How does the syntax of a while loop compare to an if statement?

Announcements

  • No Lab due Friday due to holiday
  • Midterms returned Tuesday
  • Next quiz one week from today


Review Activity


  • With a partner: Write three equivalent statements to the one below, using the shortcuts described in class:
x = x + 1;
  • With a partner: Write one statement to print the following value to the console to 5 decimal places:
final double PI = 3.1415927;

  • Imagine that a local radio station is holding a contest to give away a year's supply of free pet food to one lucky winner.
  • To win the contest, you must meet the following criteria:
    • You must be caller 19
    • The pet your own must be one of the following: dog, cat, rabbit
    • You must be between the ages of 18 and 65.
  • Which of the following test conditions will correctly determine the winner of the contest
a. if (numCaller == 19 && (pet == "rabbit" || pet == "cat" || pet == "dog") && (age >= 18 && age <= 65))
System.out.println("You are the winner!");

b. if (numCaller == 19 && (pet == "rabbit" || "cat" || "dog") && (age >= 18 && <= 65))
      System.out.println("You are the winner!");

c. 
if (numCaller == 19 || (pet.equals("rabbit") && pet.equals("cat") && pet.equals("dog")) || (age >= 18 && age <= 65))
      System.out.println("You are the winner!");


d. 
if (numCaller == 19 && (pet.equals("rabbit") || pet.equals("cat") || pet.equals("dog")) && (age >= 18 && age <= 65))
      System.out.println("You are the winner!");

e. 
if (numCaller = 19 && (pet.equals("rabbit") || pet.equals("cat") || pet.equals("dog") && (age >= 18) || age <= 65))
   
System.out.println("You are the winner!");
  • What will the following print to the console?

int age = 20;

boolean is_student = true;

if (is_student || age > 21) {

    System.out.println("Fi!");

}

if (!is_student && age < 21) {

    System.out.println("Fo!");

}

if (is_student && age < 21) {

    System.out.println("Fum!");

}


Conditional Pitfalls

  • Below are some common mistakes when using logical operators.
  • Fortunately, Java gives you an error message when you make the below mistakes.

Using = Instead of ==

  • One common mistake is to use = when you meant to use ==
  • For example, look at the test condition in the following code:
    if (guess = 7) {
        System.out.println("*** Correct! ***");
    } else {
        System.out.println("Sorry, that is not correct.");
    }
    
  • Fortunately, if you make this mistake, the Java compiler will not allow your code to run.

  • However, if you correctly use == then your code will compile
    if (7 == guess) {

Strings of Inequalities

  • Do NOT use a string of inequalities like the following:
    int a = 5, b = 1, c = 10;
    if (a < b < c) {
        System.out.println("b is between a and c");
    } else {
        System.out.println("b is NOT between a and c");
    }
    
  • Again, your code will not compile

  • Instead, the correct way is to use && as follows:
    int a = 5, b = 1, c = 10;
    if (a < b && b < c) {
        System.out.println("b is between a and c");
    } else {
        System.out.println("b is NOT between a and c");
    }
    

Strings of Logical Operators

  • Logical expressions often read like "normal" English.
  • However, Java requires more exactness than English
  • For example, the following code will compile and run but give wrong results:
    int guess;
    System.out.print("Enter a guess: ");
    guess = input.nextInt();
    if (guess == 7 || 8) {
        System.out.println("*** Correct! ***");
    } else {
        System.out.println("Sorry, that is not correct.");
    }
    
  • The above produces an error when you try to compile your code.

  • Instead, the correct way is to use || as follows:
int guess;
System.out.print("Enter a guess: ");
guess = input.nextInt();
if (guess == 7 || guess == 8) {
    System.out.println("*** Correct! ***");
} else {
    System.out.println("Sorry, that is not correct.");
}


Wrapping Up Conditionals: Switch Statements

  • The switch statement gives us an alternative to an if-else-if chain
  • Executes a section of code depending on value of a variable
  • The general syntax is:
    switch (expression) {
       case label1:
          statements
          break;
       case label2:
          statements
          break;
       ...
       case labeln:
          statements
          break;
       default:
          statements
    }
    
  • Where:
    • expression: a value you want to match
    • labelx: a numeric constant
    • statements: the statements to execute when the condition is met
  • Any number of case labels can be placed in any order
  • Any value that does not match starts executing with the statement after default
  • Execution continues until the end of the switch statement or a break statement
  • The break statement causes an immediate exit from the switch statement
  • Just as case identifies possible starting points, break determines end points

Example of a switch Statement:

public static void main(String[] args) {
	     Scanner input = new Scanner(System.in);
String typeOfDay="";

System.out.print("Enter a day of the week: ");
String dayOfWeek = input.next();

switch (dayOfWeek) {
case "Monday":
typeOfDay = "Weekday";
break;
case "Tuesday":
typeOfDay = "Weekday";
break;
case "Wednesday":
typeOfDay = "Weekday";
break;
case "Thursday":
typeOfDay = "Weekday";
break;
case "Friday":
typeOfDay = "Hurray! End of work week!";
break;
case "Saturday":
typeOfDay = "Weekend";
break;
case "Sunday":
typeOfDay = "Weekend";
break;
default:
System.out.println("Error: Invalid day of the week");

}
System.out.println(typeOfDay);
input.close();
}
  • Notice that each case other than the last contains a break statement
  • Ensures that the switch statement is exited after a matching case is found

When to Use switch Statements

  • Switch statements work for exact matches ONLY
  • They can be used with any type in Java, including ints, doubles, chars, and Strings.
  • The below example highlights the problem of only being able to look for an exact match
    • For example, we are unable to test for scores using >=
    • Thus, we have to use a clever trick - dividing the score by 10 to retrieve the first digit(s) (1-10)


Another example of switch statements involving ints


public static void main(String[] args) {
        Scanner input  = new Scanner(System.in);

        System.out.print("I show a grade based on a"
            + " score.\nEnter your score: ");
        int score = input.nextInt();

        switch (score / 10) { //integer division to convert score to an int from 1 to 10
            case 10:
            case 9:
                System.out.println("You got an A");
                break;
            case 8:
                System.out.println("You got a B");
                break;
            case 7:
                System.out.println("You got a C");
                break;
            case 6:
                System.out.println("You got a D");
                break;
            default:
                System.out.println("Sorry, an F");
        }
    }



The Case Against Switch Statements
  • Because they can only be used for exact matches (== or .equals()), switch statements are inherently less useful than if-else statements (which can involve test conditions using all 6 comparison operators, including < and >)
  • Also, the syntax is no clearer than if-else statements
  • Note that there is a reason for the limitations of the switch statement
  • Many years ago a compiler could generate more efficient code (using jump tables or binary searches) only within the limitations of the switch statement
  • However, modern compilers are quite capable of optimizing if-else statements to the same degree
  • Thus, we have no reason to ever use a switch statement (depending on your compiler)
  • On the other hand, there are reasons to avoid using a switch statement
  • Every branch of the switch statement must be terminated by a break statement
  • If the break statement is missing, the program falls through and executes the next case without testing
  • There are rare uses for this fall through behavior, such as printing the words for the song, The Twelve Days of Christmas
  • However, according to a study by Peter van der Linden, reported in his book, Expert C Programming, p. 38, the falling through behavior is needed less than 3% of the time
  • Forgetting to type the break statement is a very common error and the source of many bugs
  • Therefore, switch statements are less useful than if statements and potentially more likely to cause bugs in your code.


Example of Fall Through:

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String typeOfDay="";
        System.out.print("Enter a day of the week: ");
        String dayOfWeek = input.next();
        switch (dayOfWeek) {
             case "Monday":
                
             case "Tuesday":
                 
             case "Wednesday":
                 
             case "Thursday":
                 typeOfDay = "Weekday";
                 break;
             case "Friday":
                 typeOfDay = "Hurray! End of work week!";
                 break;
             case "Saturday":

             case "Sunday":
                 typeOfDay = "Weekend";
                 break;
             default:
                 System.out.println("Error: Invalid day of the week");
                
         }
         System.out.println(typeOfDay);
         input.close();
    }



Activity 11.1: Letter Grades Again (10 pts)
  • Find a partner for pair programming
  • Open up one partner's Assignment 9.2: Letter Grades from Canvas
  • Revise this program to use switch statements, rather than if statements.
  • For example, you will need cases that look like this:

switch(grade) {

    case "A":

        System.out.println("Numeric value: 4.0");

        break;

    //add more cases here

}


  • When you are finished revising your program, both partners should submit it to Canvas.


Introducing Loops

  • In your daily life, there are many actions that you repeat until some condition is met.
  • For example: 
    • You might run on the treadmill at the gym until 30 minutes are up.
    • You might wash dishes until the pile of dirty dishes is gone.
    • You might take classes every quarter until you receive your degree.
    • Can you think of any others?
  • When we write code, often times we find ourselves repeating statements.
  • Loops allow us to carry out repetitive steps in our code without having to re-write the same statements over and over.
  • These loops will run until some test condition is met, just like the examples above.
  • You wrote your first loops when you did your Hour of Code lab assignment.
    • When did you need loops in this assignment?

Simple Loops

  • loop is a block of code that can execute repeatedly
  • Whether or not a program repeats a block of code is determined by a test condition
  • The test condition is checked each time the loop executes
  • In general, loops have three components:
    • Initialization code
    • Test condition -- evaluated during the loop
    • Loop body with some way to change the test condition
  • There are three loop statements in Java:
    • for
    • while
    • do...while
  • We will start with the simplest of the three -- the while statement

While Loops

  • The simplest looping structure is the while statement
  • A while statement has a test condition and a body, like an if statement
  • Before each execution of the loop body, the while statement checks the test condition
  • If the test condition evaluates to true, then our program executes the body of the loop
  • When the program reaches the end of the loop body, it automatically returns to the while statement
  • Here is the syntax of a while loop:
initialization statement;

while (test)
{   

    statements to repeat

}
  • For example:
String repeat = "y";
while (repeat.equals("y")) {
System.out.print("Do you want to play again? (y/n): ");
repeat = input.next();
}
  • What does the while loop syntax remind you of?
  • The following flow chart shows how the while loop operates

Diagram of while Loop Operation

C++ while loop
Image source.

  • Let's look at an example.

Understanding the while Loop

  • The following looping application simulates the play of an exciting game
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.Scanner;

public static void main(String[] args)
{ Scanner input = new Scanner(System.in);
    String repeat = "y"; while (repeat.equals("y"))
{ System.out.println("\nPlaying an exciting game!"); System.out.println("Do you want to play again? (y/n) "); repeat = input.next(); } System.out.println("\nThanks for playing!"); }
  • Notice the structure of the code for the looping application
  • First was the statement to correctly initialize the looping condition:
    String repeat = "y";
  • Then came the while statement with the test condition
    while (repeat.equals("y"))
  • The loop executes the body of the loop if and only if the condition evaluates to true
  • Another important part of the loop is the statement: 
repeat = input.next();
  • Most loops have these parts:
    • Initialization code
    • Loop test condition
    • Loop body with some way to change the test condition
  • Question: What would happen if I replaced the while loop with an if statement?
  • We will explore the while loop more in the next exercise.

Group Activity: Candy Crush Loop

  • As a class, we are going to act out the following while loop:
While Loop :
int num_pieces_candy = 12;
instructor.fill_with_candy(Bag, num_pieces_candy);
instructor.hand_bag(first_student);
while (num_pieces_candy > 0)
{
    student.takeOnePieceCandy();
    student.passBag(next_student);
    num_pieces_candy--;

}
  • With your partner, discuss for the while loop above: 
    • What is/are the initialization statement(s)?
    • What is the loop test condition?
    • What are the statements that repeat?
    • Which statement will ultimately cause the test condition to fail?
  • Now, let's act out the While Loop!

Activity 11.2: Counting Down...
  • Grab a partner for pair programming.
  • Open up Eclipse and create a new Java project named Countdown.
  • Imagine we are at NASA Mission Control.
  • A new space ship is about to be launched.
  • Let's write a program that counts down until take off. See the sample output below:
NASA Mission Control readying for liftoff.
Initializing countdown from 10...
10
9
8
7
6
5
4
3
2
1
We have liftoff!
  • We are going to write this program in two ways.


Part 1: Repetition, Repetition, Repetition (10 pts)
  • The first program should use 13 System.out statements to achieve the above output.
  • Add your names and section in the block comments.
  • Declare an integer variable called countdown at the top of main and set it equal to 10.
  • Now, write a System.out statement to output the following:
NASA Mission Control readying for liftoff.
  • Add another System.out statement to print the following to the console:
Initializing countdown from 10...
  • Next, in a pair of statements, lets print the contents of countdown and then decrease its value by 1.
  • Add the following two statements to your code:
System.out.println(countdown);
countdown--;
  • You will need to repeat these two lines of code 10 times in your program.
  • Copy the two lines and then paste them into your program 9 more times.
  • You should have a very repetitive program by now!
  • Finally, add a System.out statement to print out "We have liftoff!" below the numbers.
  • Run your code to make sure that your output is identical to my output above.
  • When you are finished and the program is working properly, upload it to Canvas.

Part 2: Using a While Loop (10 pts)
  • Let's alter the above program to be written more efficiently with a loop.
  • First, take a look at your code.
  • Which part of the code is repetitive?
  • Hint: The repetitive lines will go inside the while loop.
  • We need a while loop to count down from the number entered by the user. Create a while loop that looks like this:
while (test will go here) {
    //statements
}
  • What should go inside the test?
countdown > 0
  • Why do you use > 0 here?
  • Inside the curly braces of the while loop, we need to print out the contents of the countdown variable and then decrease its value by 1.
  • Take one of your pairs of System.out statement and variable decrement and place it in the curly braces of the while loop.
  • Now, you can erase the other 9 pairs of statements.
  • Finally, below your while loop, there should now be only one System.out statement
  • Run your program to make sure it is working the same as before.
  • When you are finished, upload this new version to Canvas.

About those Curly Braces

  • Like the if-statement, the curly braces of a while loop are optional
  • Technically, the while statement affects only the single statement that follows
  • We use curly braces to make that one statement into a block of statements
  • This allows us to put any number of statements within the body
  • Curly braces are not always required, but the best practice is to always include them

Program Style: Indent Statements Inside a Loop

  • It is important to format the loop code correctly:
    String repeat = "y";
    while (repeat.equals("y")) {
        // ... statements to repeat
        repeat = input.next();
    }
Also Accepted Style:
        String repeat = "y";
    while (repeat.equals("y"))
    {
        // ... statements to repeat
        repeat = input.next();
    }
  • Note how the repeated code is indented inside the loop
  • This lets us see easily which code is repeated and which is not
  • Also note the placement of curly braces
  • Different groups have different practices for placing curly braces in a loop statement



Wrap Up

  • With your partner, answer the questions from today's learning objectives


Upcoming Assignments

  • No Lab due Friday