/** * */ import java.io.*; public class Guessing { public static void main(String[] args) { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); int max = 1024; if (args.length > 0) max = Integer.parseInt(args[0]); int target = (int)(max * Math.random()); System.out.println("Hi, I'm thinking of a number between 0 and " + max); int guess = getIntPrompted("Your guess, please: ", input); int guesses = 1; while (guess != target) { if (guess < target) guess = getIntPrompted("Too low, try again: ", input); else guess = getIntPrompted("Too high, try again: ", input); guesses++; } System.out.println("Got it (" + guesses + " guesses)"); } public static int getIntPrompted(String prompt, BufferedReader input) { try { System.out.print(prompt); String text = input.readLine(); return Integer.parseInt(text); } catch (Exception e) { System.out.println(" That was not a proper number, try again."); return getIntPrompted(prompt,input); } } }