Lab #5: Number Guessing Game

The goal of this lab is to write a class GuessingNumber that plays a number guessing game with the user.

Using the Math.random() it is possible to generate a random integer between 1 and an integer N. Since Math.random() produces a random real number between 0 and 1, excluding 1, Math.random()* N produces a random real number between 0 and N, excluding N itself. So, the formula (int)(Math.random() * N) produces a random integer between 0 and N-1, and thus, 1 + (int)(Math.random() * N) produces a random integer between 1 and N.

The game will be played by a void method called playGame that takes two parameters, the maximum number (called maximum) and the number of rounds (called noRounds). The way the method works is as follows:

  1. The program generates a secret random number according to the formula using the formula in the above.
  2. The method explains the nature of the game to the user.
  3. The user then makes a guess at most noRounds times. The program uses a for-loop to count down from noRounds to 1. In the loop-body, if the guess is already equal to the number secret, nothing will happen; otherwise, the user is asked to make a guess and the program receives the guess, and then if the guess is greater or smaller than the secret number the program tells the user which side the guess has fallen.

Here is an example of execution with the two parameter values, 2000 and 10:

% java GuessingNumber
---I have a number between 1 and 2000.
---You can make up to 10 guesses.
---If your guess is incorrect,
---I will tell you whether the guess is greater or smaller than my number.
---Hit return to start: 1000
---You have 10 guesses remaining.
---Enter your guess: 1000
---Your guess is greater.
---You have 9 guesses remaining.
---Enter your guess: 500
---Your guess is smaller.
---You have 8 guesses remaining.
---Enter your guess: 750
---Your guess is greater.
---You have 7 guesses remaining.
---Enter your guess: 675
---Your guess is smaller.
---You have 6 guesses remaining.
---Enter your guess: 710
---Your guess is greater.
---You have 5 guesses remaining.
---Enter your guess: 700
---Your guess is greater.
---You have 4 guesses remaining.
---Enter your guess: 690
---Your guess is greater.
---You have 3 guesses remaining.
---Enter your guess: 682
---Your guess is smaller.
---You have 2 guesses remaining.
---Enter your guess: 684
---Your guess is smaller.
---You have 1 guesses remaining.
---Enter your guess: 685
---You've got it!

You may use this template: GuessingNumber.java

Go back to the lab main page

Go back to the home page