/** One interesting thing about implementing this guessing game program * is that nowhere in the code do we ever see what the answer really is. * This "Guess" class creates the number we should guess, and like the * dice game program uses Java's built-in Random number generator. * Note we have 4 attributes to the game, including keeping track of how * we are with the number of guesses. */ import java.util.Random; public class Guess { private int correctAnswer; private int numGuesses; private int maxGuesses; private Random generator; /** Create a number we should guess in the range 1-100. */ public Guess() { generator = new Random(); // initialize random number generator correctAnswer = generator.nextInt(100) + 1; maxGuesses = 7; numGuesses = 0; } /** Determine if the user's guess is correct. If it is not, indicate * which way we should go for the next guess. */ public boolean good(int userGuess) { ++numGuesses; if (userGuess == correctAnswer) return true; else if (userGuess > correctAnswer) { if (numGuesses < maxGuesses) { System.out.printf("too big\n"); } return false; } else { if (numGuesses < maxGuesses) { System.out.printf("too small\n"); } return false; } } /** Find out if we have exhausted the number of allowable guesses. * Note that the outcome of ">=" is either true or false. */ public boolean youLose() { return numGuesses >= maxGuesses; } /** At end of game, it may be useful to tell the user what the correct * answer was. */ public int giveAnswer() { return correctAnswer; } }