Java Reference
In-Depth Information
This pseudocode leads us to write the following Java program. Note that the com-
puter always picks the value
42
in this version of the program:
1
import
java.util.*;
2
3
public class
NumberGuess1 {
4
public static void
main(String[] args) {
5 Scanner console =
new
Scanner(System.in);
6
int
number = 42; // always picks the same number
7
8 System.out.print("Your guess? ");
9
int
guess = console.nextInt();
10
int
numGuesses = 1;
11
12
while
(guess != number) {
13 System.out.println("Incorrect.");
14 System.out.print("Your guess? ");
15 guess = console.nextInt();
16 numGuesses++;
17 }
18
19 System.out.println("You got it right in " +
20 numGuesses + " tries.");
21 }
22 }
We can test our initial program to verify the code we've written so far. A sample
dialogue looks like this:
Your guess?
65
Incorrect.
Your guess?
12
Incorrect.
Your guess?
34
Incorrect.
Your guess?
42
You got it right in 4 tries.
Now that we've tested the code to make sure our main game loops, let's make the
game random by choosing a random value between
00
and
99
inclusive. To do so,
we'll create a
Random
object and call its
nextInt
method, specifying the maximum
Search WWH ::
Custom Search