Java Reference
In-Depth Information
14
}
15
if (guess < number)
{
16
System . out . p r i n t l n ( "Go higher" );
17
continue ;
18
}
19
System . out . p r i n t l n ( "You got it!" );
20
break ;
21
}
22
23
if (numTries == 10) {
24
System . out . p r i n t l n ( "You ran out of guesses" );
25
System . out . p r i n t l n ( "My number was: " + number) ;
}
26
27
}
28
}
This time, we need the value of the counter variable after the for loop is executed. This is
why Line 7 declares the variable numTries before the loop. The for loop uses two interesting
commands: continue and break . While we have seen the break command before, the
continue command is new. The command continue means: stop executing this iteration
of the for loop and go to the next iteration. In our program, the statement continue
means: jump to the third part of the for loop, that is, to the expression numTries++ .Ifwe
have determined that the guess is too high or too low, then we simply let the player know
that and execute the continue statement in order to jump to the next iteration. If Line 19
is being executed, then this means that neither condition is true, that is, the player guessed
the number correctly. In this case, we let the player know that they won and exit the for
loop using the break statement.
In the new version of the program, we are not sure if the player guessed the number
correctly at Line 23. We could have terminated the for loop because the counter reached
10 or because the player guessed the correct number. Therefore, we need to check the value
of the counter variable at Line 23. If it is equal to 10, then this means that the player was
unsuccessful in guessing the number and we need to print an appropriate message.
3.4 Nested for Loops
No game is complete without some good artwork. Drawing graphics involves advanced
programming techniques and it and will be covered in Chapter 9. For now, we need to
content ourselves with drawing ASCII art, that is, pictures from characters. Our next task
is to create a program that displays a diamond of stars.
∗∗∗
∗∗∗∗∗
∗∗∗
The size of the diamond (i.e., the number of stars in the middle line) will be a parameter
of the program. In the above picture, the size of the diamond is equal to 5. Note that the
size of the diamond must be an odd number.
We will solve the problem by using the popular divide-and-conquer approach. The first
part of the program will print the top half, while the second part of the program will print
 
Search WWH ::




Custom Search