Reading:

5.1-5.3 Selection and if Statements

What do the following code segments do. Consider different values for the variable guess ?

int guess = 3;

// 1
if (guess <= 5) {
   println("The Cat in the Hat");
}

// 2
if (guess == 5) {
   println("Hop on Pop");
} else {
   println("Horton Hears a Who");
}

// 3
if (guess != 5)
   println("Green Eggs and Ham");

// 4
if (guess <= 5)
   println("The Cat in the Hat");
   println("Comes Back");
   
// 5
if (1 < guess < 5) {
   println("And to Think that I Heard it on Mulberry Street");
}

// 6
if (guess = 5) {
   println("How the Grinch Stole Christmas");
}

// 7
if (guess == 5);
   println("The Lorax");

Explain what happens with these statements and why. Are there compile-time errors, run-time errors, logic errors? If the statement doesn't work as one might expect, modify it so that it does.

Now, declare and initialize a string variable, guess and try to write selection statements that do the following:

Vary the value of guess to assure yourself that your statements handle all cases properly. Note that you might consider programming your equivalence conditions as either guess == "mike" or as guess.equals("mike") . Which of these forms works appropriately? Why? See Chapter 3, Section 3.3.5 for details on this issue.

5.4. Using the switch Statement

Skip this section for now, we’ll return to it later in the course.