CS-151 Labs > Lab 1. The First Cup of Java
Part 2. Guess the number
For this part, we want you to create a class called HiLo
that plays a simple
numeric guessing game. The computer will pick a random number between 1 and 1000 and
then the user will try to guess what it is.
To get a random number, you will need to create a random number generator rng
using Java
Random
class. You will need to import java.util.Random
to make it available to your program.
You then can use rng.nextInt(1000)
to get a number between 0 and 999.
Just add 1 to shift it into the desired range.
Random rng = new Random();
int target = rng.nextInt(1000) + 1;
Now you’ll want to loop until the user guesses your number. You can use break
and continue
to exit from or to go to the next iteration of a loop.
Use a Scanner
object to read from System.in
which will capture keyboard input.
If the line doesn’t start with a number (i.e., hasNextInt()
returns false), then you
should print a message out to the user and ask the user to enter the number again.
Keep track of the total number of guesses the user makes and let them know how they did at the end.
Sample program run:
Let's play a game!
I'm thinking of a number between 1 and 1000
Try to guess what it is!
Enter a guess: 500
Too low!
Enter a guess: 750
Too high!
Enter a guess: 625
Too low!
Enter a guess: -72
Too low!
Enter a guess: kittens
That's not a number, try again.
Enter a guess: 630
Too high!
Enter a guess: 629
You guessed my number! It took you 6 tries.