import java.util.Scanner; import java.util.Random; public class GuessNumber { private static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) { Random rand = new Random(); int secretNumber = rand.nextInt(10); int numGuesses = playGame(secretNumber); System.out.println("# guesses: " + numGuesses); } /* Repeatedly asks user to enter an integer "guess" at the keyboard ** until such time as their guess is equal to the given number (targetNum). ** Returns the # of guesses that the user made. ** pre: targetNum >= 0 */ public static int playGame(int targetNum) { int guess = getInt("Enter your first guess: "); int count = 1; // guesses made so far while (guess != targetNum) { guess = getInt("Wrong; try again: "); count = count + 1; } return count; } /* Prompts user to enter an integer guess, reads the response, ** and returns it to the caller. */ private static int getInt(String prompt) { System.out.print(prompt); return keyboard.nextInt(); } }