/* Simulation of console-I/O program GuessingGame, using ConsoleApplet as a basis. See the file ConsoleApplet.java for more information. David Eck eck@hws.edu August 11, 1996 */ public class GuessingGameConsole extends ConsoleApplet { public void init() { title = "Sample program \"GuessingGame\""; super.init(); } protected void program() { /* The user plays a guessing game where the computer picks a number between 1 and 100, and the user tries to guess the number */ console.putln("Let's play a game. I'll pick a number between"); console.putln("1 and 100, and you try to guess it."); boolean playAgain; do { playGame(); // call subroutine to play one game console.put("Would you like to play again? "); playAgain = console.getlnBoolean(); } while (playAgain); } // end program() void playGame() { int computersNumber = (int)(100 * Math.random()) + 1; // The value assigned to computerNumber is a randomly // chosen integer between 1 and 100, inclusive int usersGuess; // this will be a number entered by user console.putln(); console.put("What is your first guess? "); do { usersGuess = console.getInt(); if (usersGuess == computersNumber) console.putln("You got it! My number was " + computersNumber); else if (usersGuess < computersNumber) console.put("That's too low. Try again: "); else if (usersGuess > computersNumber) console.put("That's too high. Try again: "); } while (usersGuess != computersNumber); console.putln(); } // end of playGame() } //end class GuessingGameConsole