Lab: Guessing Game

Collaboration: Complete this with other person from your section during your scheduled lab.

Grading: For 100%, don't be late to lab and stay to end of lab –or– complete GuessingGame.

Recommended Activities:

  1. Review the Java while loop
  2. Play a sequential (no hints) guessing game to guess a number from 1..100
  3. Play a binary search (with hints) guessing game to guess a number from 1..100
  4. Describe Random objects and the nextInt(int) message

This lab requires the use of random numbers. Java has a class named Random that makes it easy to get seemingly random numbers into your program. After you import the Random class

import java.util.Random;

you can construct a Random object like this

Random randomNumberGenerator = new Random();

and then use Java's nextInt method:

// From the Random class

// Return a seemingly random integer in the range of 0 through n-1.

public int nextInt(int n)

For example, you can get a number from 0 to 5 with this message:

// The message returns 1, 2, 3, 4, 5, or 6. It appears to be random.

int randomNumber = randomNumberGenerator.nextInt(6) + 1;

  1. In teams of two, write a Java class that implements a guessing game. Ask the user for a number in the range of 1 through largest inclusive where the largest is entered by the user. A good value would be 100 (after a few games, try 1000, which should take only 3 more guesses with smart inputs). If the guess is larger than the random number you generated in the range of 1 through largest (100 below), inform the user that the guess was too high. If the guess is too low, tell that to the user. When the guess matches the random number, tell that to the user. Here is a sample dialogue when the user enters 100 as the largest number allowed:

Enter largest number: 100

Pick a number from 1..100: 50

50 is too high

Pick a number from 1..100: 25

25 is too high

Pick a number from 1..100: 12

12 is too low

Pick a number from 1..100: 18

18 is just right

Congrats, you needed 4 guesses

When done, raise your hand to get your section leader to give you credit.