// 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 e3sol {
    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 = myRandom(LOW,HIGH);
	   // "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 ) {
	       // Check quality of guess:
	          checkGuess(guess,target);
	       // 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);
	   }
	   
    }

    // Pick a random number between LOW and HIGH:
       public static int myRandom(int LOW, int HIGH) {
	   return (int) ( Math.random()*(HIGH-LOW+1) + LOW );
       }

    // Report quality of $guess$:
       public static void checkGuess(int guess, int target) {
	   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!");
       }

}

