/* Author: Stephanie Elzer * Date: March 25, 2007 * Purpose: To demonstrate loops while playing a guessing game */ import java.util.*; public class GuessGame { /** * @param args */ // This method plays a single round of the guessing game. If the user quits the game, a -1 is returned, otherwise // the number of guesses it took them to get the number is returned. public static int PlayGuessGame() { Random generator = new Random(); // Other variable declarations int guess, count = 0; Scanner scan = new Scanner(System.in); // Generate a random number and reset count of guesses int randNum = generator.nextInt(100) + 1; count = 0; // Play the guessing game do { // Read in a guess System.out.print("Enter a guess (between 1 and 100, or -1 to stop):"); guess = scan.nextInt(); // If the user doesn't want to quit, count the number entered as a guess if (guess != -1) count++; // Display "too high" or "too low" as appropriate if ((guess < randNum) && (guess != -1)) System.out.println("Too low!"); else if (guess > randNum) System.out.println("Too high!"); } while ((guess != randNum) && (guess != -1)); // Print out results of the game if (guess != -1) { System.out.println("You got it in " + count + " tries."); return count; } // If the user quit, return -1 as the result else { System.out.println("Quitter!"); return -1; } } public static void main(String[] args) { // TODO Auto-generated method stub // Set up scanner and random number generator Scanner scan = new Scanner(System.in); int count = 0, totalcount = 0; int games = 0; String another; // Allow user to play the game as many times as they would like do { count = PlayGuessGame(); // If the user didn't quit out of the game, accumulate the statistics if (count!= -1) { totalcount += count; games++; } // See if the user wants to play again System.out.print("Do you want to play again (yes/no)? "); another = scan.next(); } while (another.equalsIgnoreCase("yes")); // Calculate average number of guesses double average = 0; if (games >= 1) average = (double)totalcount / games; System.out.println("Average guesses: " + average); System.out.println("Exiting..."); } }