Java Reference
In-Depth Information
for (numTries = 0; numTries < =9; numTries++) {
...
System. out . println (numTries) ;
The code in the block will be executed 10 times. Let us next show an implementation
of our game using the for loop.
1
import java . util . ;
2
3 public class GuessGame
{
4
public static void main(String [] args)
{
5
int number = ( int )
(Math . random ( )
1000) ;
6
Scanner keyboard = new Scanner(System. in) ;
7
for ( int numTries = 0; numTries
<
10; numTries++)
{
8
System . out . p r i n t l n ( "Enter your guess: " );
9
int guess = keyboard . nextInt () ;
10
if ( guess == number)
{
11
System . out . p r i n t l n ( "You got it!" );
12
return ;
13
}
14
if (guess > number) {
15
System . out . p r i n t l n ( "Go lower" );
16
}
else
{
17
System . out . p r i n t l n ( "Go higher" );
18
}
19
}
20
System . out . p r i n t l n ( "You ran out of guesses" );
21
System . out . p r i n t l n ( "My number was: " +number) ;
22
}
23
}
Line 5 creates a random number between 0 and 999. Lines 7-19 create a for loop
that is executed 10 times. If the player enters the correct guess (Line 10), then we print an
appropriate message (Line 11) and terminate the program (Line 12). Otherwise, we compare
the player's guess with the chosen number and tell the player to go higher or lower. Note
that Lines 20-21 will only be executed if the return statement on Line 12 is never executed,
that is, the player was unsuccessful in guessing the number in ten tries.
Sometimes, we may want to execute more code after the game ends (e.g., start a different
game). In this case, exiting the program when the user enters the correct guess is not the
right option. An alternative implementation that does not use the return statement is
shown next.
1
import java . util . ;
2
3 public class GuessGame
{
4
public static void main(String [] args)
{
5
int number = ( int )
(Math . random ( )
1000) ;
6
Scanner keyboard = new Scanner(System. in) ;
7
int numTries ;
8
for (numTries = 0; numTries < 10; numTries++) {
9
System . out . p r i n t l n ( "Enter your guess: " );
10
int guess = keyboard . nextInt () ;
11
if (guess > number)
{
12
System . out . p r i n t l n ( "Go lower" );
13
continue ;

Search WWH ::

Custom Search