// Number-guessing game // Code fragments by DIS // Number-guessing game // commenting style borrowed from Gries's recommendation // (see on-line style guide) // Load Java's I/O facilities: import java.io.*; public class p2NumberGuess { public static void main(String[] args) throws IOException { // Initialize variables: int guess; // human guess of $target$ int count; // number of guesses to reach $target$ final int LOW=0; // lowest value of $target$ final int HIGH=100; // highest value of $target$ final int STOP=HIGH-LOW; // maximum number of guesses // Computer guesses a random number in [LOW,HIGH]: int target = (int) ( Math.random()*(HIGH-LOW+1) + LOW ); // "Magic" code for obtaining user input: BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); // Welcome user and explain rules: System.out.println("Welcome to my number guessing game!"); System.out.println("You must pick a number between 0 and 100"); System.out.println("in the fewest number of guesses."); System.out.println("Enter a number outside of [0,100] to quit" + " prematurely."); // User makes 1st guess: System.out.print("\nGuess an integer: "); guess = Integer.parseInt(in.readLine()); count = 1; // Check guesses and report closeness to user: while ( guess != target && guess >= LOW && guess <= HIGH && count <= STOP ) { // Report quality of $guess$: if (guess < target) System.out.println(guess + " is too low. Try again!"); else if (guess > target) System.out.println(guess + " is too high. Try again!"); // User makes next guess: System.out.print("\nGuess an integer: "); guess = Integer.parseInt(in.readLine()); // Increment $count$ of guesses: count++ ; } // Report results: if (target == guess) { System.out.println("\nCongratulations!\n"); System.out.println("You guessed the correct" + " answer of " + target + " in " + count + " guesses."); } else if(count > STOP) { System.out.println("\nI'm sorry, but you made more guesses"); System.out.println(" than numbers in the acceptable range."); } else if(guess < LOW || guess > HIGH) { System.out.println("\nOK, I'm stopping after "+ (--count) + " valid guesses."); System.out.println("The correct answer was " + target + "."); } else { System.out.println("Something went horribly wrong, so I am" + " exiting."); System.exit(0); } } }