In class on Friday we talked about nested if statements and ambiguous else statements. In particular, we looked at the code:
if ( hr < 9 ) if ( randNum == 0 ) System.out.println("Good morning!"); else System.out.println("Hi!");
This is actually legal (if unreadable) code, even without braces,
because in Java an if/else
statement, or even an
if/else if/else if/else
statement, is considered
a single, complex statement.
The other important thing to know about Java in order to understand the
code above is that when there is an ambiguous else
, as in
this example (is it the else
for the first if
or the second if
?), it always associates with the most
recent if
.
This means that the code above is equivalent to
if ( hr < 9 ) { if ( randNum == 0 ) System.out.println("Good morning!"); else System.out.println("Hi!"); }
In other words, if it is before 9 o'clock and if the random number is 0, then the code will print "Good morning!" If it is before 9 o'clock but the random number is something other than 0, it will print "Hi!" If the hour is 9 or later, nothing will be printed.
As someone mentioned in class, it is also equivalent to:
if ( hr < 9 && randNum == 0 ) { System.out.println("Good morning!"); } else if ( hr < 9 ) { System.out.println("Hi!"); }
We then asked how we could change the code if we wanted to print "Good morning!" when the time is before 9 o'clock (but only if the random number is 0), and print "Hi!" when the time is 9 or later. In this case we would print nothing when the time is before 9 but the random number is not 0. Three valid ways of doing this were proposed.
// Alternative 1 if ( hr < 9 && randNum == 0 ) System.out.println("Good morning!"); else if ( randNum != 0 ) System.out.println("Hi!");
// Alternative 2 if ( hr < 9 ) if ( randNum == 0 ) System.out.println("Good morning!"); else ; else System.out.println("Hi!");
// Alternative 3 (the one I showed on the screen) if ( hr < 9 ) { if ( randNum == 0 ) System.out.println("Good morning!"); } else System.out.println("Hi!");