import javax.swing.*; /** * A game for guessing a number, where the user is told the range the * solution is in based on their guesses. */ public class GuessingRange { /** The number to be guessed */ private int solution; /** * A GuessingGame with solution n. * @param n the number to be guessed. */ public GuessingRange(int n) { this.solution= n; } /** * Play the guessing game. Continually prompt the user for a guess until * they guess the solution. Let them know whether their guesses are too * high or too low, and also tell them the range the solution is in (based * on their previous guesses). */ public void play() { // The beginning of the message where the user guesses too low. final String LOW_MESSAGE= "Your guess was too low. " + "You know that the number is in the range\n"; // The beginning of the message where the user guesses too high. final String HIGH_MESSAGE= "Your guess was too high. " + "You know that the number is in the range\n"; // The end of the message. final String MESSAGE_END= ", inclusive. Guess again."; String upper= ""; // The upper end of the range the solution is in. String lower= ""; // The lower end of the range the solution is in. String message= "Guess an integer."; // The message for the user. // The current guess. int guess= Integer.parseInt(JOptionPane.showInputDialog(message)); int numGuesses= 1; // The number of times the user has guessed. // Keep going until the user guesses correctly. while (guess != this.solution) { // Is the user guess too high? if (guess > this.solution) { if (upper.equals("") || guess <= Integer.parseInt(upper)) { upper = "" + (guess - 1); } message= HIGH_MESSAGE + lower + ".." + upper + MESSAGE_END; } else { // The user guess is low. if (lower.equals("") || guess >= Integer.parseInt(lower)) { lower = "" + (guess + 1); } message= LOW_MESSAGE + lower + ".." + upper + MESSAGE_END; } guess= Integer.parseInt(JOptionPane.showInputDialog(message)); numGuesses++; } message= "You're right! You used " + numGuesses + " guesses."; JOptionPane.showMessageDialog(null, message); } }