/* * NumberGuess.java * * Created on October 18, 2007, 1:06 PM * * Program allows the user to guess a number in a * limited number of tries. */ package numberguess; /** * * @author Andrew */ import TerminalIO.KeyboardReader; import java.util.Random; public class NumberGuess { /** Creates a new instance of NumberGuess */ public NumberGuess() { } /** * @param args the command line arguments */ public static void main(String[] args) { int theNumber = 0; //number to guess int theGuess = 0; //number the user enters int theTries = 5; //varibale tracks number of tries KeyboardReader reader = new KeyboardReader();// //User instructions System.out.println("The number guessing game!"); //System.out.println("The guess is: " + theGuess); // generate the number to guess Random generator = new Random(); theNumber = (generator.nextInt(19)+1); System.out.println("The random num is: " + theNumber); // loop for as many tries as allowed while(theTries>0) { // prompt for guess System.out.println("Guess a number between 1-20."); theGuess = reader.readInt(); // test for win; otherwise decrement and loop again theTries--; //decrement loop control if (theGuess < theNumber) //guess too high System.out.println("Too low."); else if(theGuess > theNumber) System.out.println("Too high."); else { System.out.println("you win!"); theTries = -1; //set theTries to 0 to exit }//end else of win test } //ends while loop if (theTries == 0)//true if all tries used { System.out.println("Sorry, you did not guess it."); System.out.println("The number was: " + theNumber); }//end of true for zero theTries eq zero } //closes main } //closes class