Java Reference
In-Depth Information
With nested
if
s, the question of which
if
statement a particular
else
clause belongs to often arises. If
you remove the braces from the preceding code, you have:
if(number%2 == 0) // Test if it is even
if(number < 50 ) // Output a message if number is < 50
System.out.println("You have got an even number < 50, " + number);
else
System.out.println("You have got an odd number, " + number); // It is odd
This has substantially changed the logic from the previous version, in spite of the fact that the indentation
implies otherwise. The
else
clause now belongs to the nested
if
that tests whether
number
is less than 50,
so the second
println()
call is executed only for
even
numbers that are greater than or equal to 50. This is
clearly not what was intended because it makes nonsense of the output in this case, but it does illustrate the
rule for connecting
else
s to
if
s, which is:
An
else
always belongs to the nearest preceding
if
in the same block that is not already spoken for by
another
else
.
You need to take care that the indenting of statements with nested
if
s is correct. It is easy to convince
yourself that the logic is as indicated by the indentation, even when this is completely wrong.
Let's try the
if-else
combination in another program.
TRY IT OUT: Deciphering Characters the Hard Way
Create the class
LetterCheck
, and code its
main()
method as follows:
public class LetterCheck {
public static void main(String[] args) {
char symbol = 'A';
symbol = (char)(128.0*Math.random());
// Generate a random
character
if(symbol >= 'A') {
// Is it A or
greater?
if(symbol <= 'Z') {
// yes, and is it Z
or less?
// Then it is a capital letter
System.out.println("You have the capital letter " + symbol);
} else {
// It is not Z or
less
if(symbol >= 'a') {
// So is it a or
greater?
if(symbol <= 'z') {
// Yes, so is it z
or less?
// Then it is a small letter
System.out.println("You have the small letter " + symbol);