Chapter 6: Selection Statements - Making decisions


Topics


If Statements

The following is the syntax for a valid if statement:

if (<conditional expression>)
    <java statement>

-or-

if (<conditional expression>)
    <java statement>
else
    <java statement>

Example 1:

int temperature = inBox.getInteger(
                  "Enter your temperature.");
if (temperature > 101)
    outBox.printLine("Go home to rest. " + 
                     " You are really sick!");

Example 2:

int x = 
    inBox.getInteger("Enter your answer (1=yes, 0=no)");
if (x==1)
    outBox.printLine("You have answered yes.");
else
    outBox.printLine("You have answered no.");

Note the indentation convention.


Conditional Expressions

Conditional expressions are expressions that evaluate to boolean values, that is, either true or false.

Comparison operators can be used to create boolean expressions:

Table of Comparison Operators

Operator

Meaning

Examples

Value

==

equals

4 == 16

false

<

less than

4 < 16

true

>

greater than

4 > 16

false

<=

less than or equal

4 <= 16

true

>=

greater than or equal

4 >= 16

false

!=

not equal

4 != 16

true

Other examples of conditional expressions (what do they evaluate to?):

5.4 < 100.5

(5+23) < (45/78)

width != 10

1 == dice.roll()

Java Statements

For the <java statement> you can fill in any valid statement. Examples include the following:

Let us see how the rules are applied:

Example 1:

int temperature = 
   inBox.getInteger("Enter your temperature.");
if (temperature <= 95)
   outBox.printLine("You have a low body temperature.");
else
   outBox.printLine("You do not have a low body temperature.");

Example 2: Method for asking a yes/no question:

public boolean ask(String question)
{ int x = inBox.getInteger(question + " (1=yes, 0=no)"); if (x==1) return true; else return false; }

Example 3: Using rule 4, we can replace the temperature output statement with

{
   int pulse = inBox.getInteger("What is your heart rate?");
   outBox.printLine("Your heart rate is " + pulse);
}

to give:

int temperature = inBox.getInteger("Enter your temperature.");
if (temperature <= 95) // low body temperature
{
   int pulse = inBox.getInteger("What is your heart rate?");
   outBox.printLine("Your heart rate is " + pulse);
}
else
   outBox.printLine("You do not have a low body temperature.");


Nested If-Statements

By Rule 4, we could add more valid statements between the curly braces, including valid if statements:

int temperature = inBox.getInteger("Enter your temperature.");
if (temperature <= 95) // low body temperature
{
   int pulse = inBox.getInteger("What is your heart rate?");
   outBox.printLine("Your heart rate is " + pulse);
   if (pulse > 0)
      outBox.printLine("Draw a hot bath for yourself.");
   else
      outBox.printLine("Better call the morgue.");
}
else
   outBox.printLine("You do not have a low body temperature.");

Similarly, we could substitute another if statement for the last output statement in the else clause:

int temperature = inBox.getInteger("Enter your temperature.");
if (temperature <= 95) // low body temperature
{
   ....
}
else
{
   if (temperature > 101) // fever
      outBox.printLine("You have a fever!");
   else // normal temperature
      outBox.printLine("Your temperature is normal.");
}

Notes on Indentation

Note that the syntax rule for the if-statement implies an indentation scheme for laying out an if statement on the screen. When one if-statement appears inside another, some lines are indented two levels, because the inner if-statement is itself indented one level. If an if-statement is then substituted inside one of these if-statements, some statements will end up indented three levels deep, etc.

Though the compiler pays no attention to the indentation, you should always follow this indentation scheme in order to make your program comprehensible to yourself, instructors, and other programmers.


Multi-way If-Else Statements

There is one exception to this indentation scheme. Let us add a new syntax rule regarding indentation. The three places where there are comments about fever correspond to three mutually exclusive conditions (low, high, or normal body temperature).

In such a case, it is acceptable to indent the if and else clauses having to do with these conditions at the same level of indentation. For example:

int temperature = inBox.getInteger("Enter your temperature.");
if (temperature <= 95) // low body temperature
   outBox.printLine("You have low body temperature.");
else if (temperature > 101) // fever
   outBox.printLine("You have a fever!");
else // normal temperature
   outBox.printLine("Your temperature is normal.");

In general, any set of mutually exclusive conditions can be handled in this way.

Let us formalize this indentation scheme with an additional syntax rule for the if statement. The following is also a valid if statement:

if (<conditional expression>)
   <java statement>
else if (<conditional expression>)
   <java statement>
else if (<conditional expression>)
   <java statement>
...
else
   <java statement>

This tells the computer to find the first valid conditional expression in the series that evaluates to true, to execute the java statement immediately under it, and then to skip the remainder of the series.

Another Example:
Have the user enter a number from 1 to 12 corresponding to the index of the month. The program then prints out the name of the month:

if (num == 1)
   outBox.printLine("January");
else if (num == 2)
   outBox.printLine("February");
else if (num == 3)
   outBox.printLine("March");
...
else if (num == 12) outBox.printLine("December"); else outBox.printLine("Not a valid month.");


Order Matters

Consider the example to print out “big” if a number is bigger than 100, “medium” if a number is between 20 and 100, and small otherwise. The code would be

if (num > 100)
  outBox.printLine("Big");
else if (num > 20)
  outBox.printLine("Medium");
else
  outBox.printLine("Small");

Why does the second condition (num>20) only get executed for numbers between 20 and 100? If the order of the if statements had been rearranged:

if (num > 20)
   outBox.printLine("Medium");
else if (num > 100)
   outBox.printLine("Big");
else 
   outBox.printLine("Small");

would this work properly?


Boolean Operators: AND, OR, NOT

Boolean operators take boolean operands and return boolean values.

AND:

a

b

a && b

true

true

true

true

false

false

false

true

false

false

false

false

OR:

a

b

a || b

true

true

true

true

false

true

false

true

true

false

false

false

NOT:

a

!a

true

false

false

true

Using Java syntax, write a boolean expression that evaluates to true when:


Boolean Algebra

false || a = a

a || b = b || a

a || (b && c) = (a || b) && (a||c)

a || (!a) = true

a || a = a

! (a || b) = !a && !b


Switch Statements

Switch statements are a special case of multi-way if-else statements. That is, all switch statements can be written as multi-way if-else statements but not vice versa.

switch (e) 
{
   case v1:
      <java statement>;
      <java statement>;
      ...
      break;
   case v2:
      <java statement>;
      <java statement>;
      ...
      break; 
   case v3:
      <java statement>;
      <java statement>;
      ...
      break; 
   ...
default: // this is optional <java statement>; <java statement>; ...
}

Where:

Example 1:
Converts the day of the in numeric form (1, 2, ... 7) to the name of the day (Sunday, Monday,...)

String name="not a day";
int day = inBox.getInteger(
  "Enter a number for the day of the week " + 
  "(1=Sunday,2=Monday, ..): ");
switch(day)
{
   case 1:  
      name = "Sunday";
      break;
   case 2:
      name = "Monday"; 
      break; 
   case 3:
      name = "Tuesday";
      break;
   case 4: 
      name = "Wednesday";
      break;
   case 5:
      name = "Thursday";
      break;
   case 6:
      name = "Friday";
      break;
   case 7:
      name = "Saturday";
      break;
}
outBox.printLine("The day you entered is " + name);

Example 2:

switch(day)
{
   case 1:
   case 7:
      name = "Weekend";
      break;
   case 2:
   case 3:
   case 4:
   case 5:
   case 6:
      name = "Weekday";
}
outBox.printLine("It is a " + name);


next lecture