/* High/Low Game #2 written by Keith Fenske Tuesday, 23 April 2002 Copyright (c) 2002 by Keith Fenske. All rights reserved. This Java program plays a simple guessing game. The computer picks a random number from 0 to 100, and the user tries to guess the number. This the second version of the High/Low game. A separate "while" loop is used to check the user's input. */ import cs1.Keyboard; // import Lewis/Loftus keyboard class // http://duke.csc.villanova.edu/jss/keyboard.html public class HighLow2 { public static void main(String[] args) { boolean ask; // true while we are asking for a guess int number; // the computer's random number int guess; // the user's guess System.out.println("\nWelcome to the High/Low game."); System.out.println("I will pick a random number from 0 to 100."); System.out.println("You must try to guess the number."); number = (int) (Math.random() * 101); do { // ask the user for a guess ask = true; // true until we get a good guess guess = 50; // initial value to make JBuilder happy while (ask) { System.out.print("\nWhat is your guess? (0 to 100) "); guess = Keyboard.readInt(); if ((guess >= 0) && (guess <= 100)) ask = false; // this number is okay, so stop asking else { System.out.println("Sorry, but your guess " + guess + " must be from 0 to 100."); } } // check the user's guess against our random number if (guess < number) { System.out.println(guess + " is low. Try a higher number."); } else if (guess > number) { System.out.println(guess + " is high. Try a lower number."); } else // equal { // number is correct, and the "do" loop will end below System.out.println(guess + " is correct. Congratulations!"); } } while (guess != number); System.out.println("Thank you for playing High/Low!"); } }