import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class GuessANumber{ private Random rnd; private boolean isAnInt(String input){ try{ int output = Integer.parseInt(input); return true; }catch(Exception ex){ return false; } } private int getNumericInput(String prompt){ while(true){ System.out.print(prompt + ": "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ String ans = br.readLine(); if(isAnInt(ans)) return Integer.parseInt(ans); System.out.println("Your entry was not a number"); }catch(Exception ex){ } } } private String getInput(String question){ while(true){ System.out.println(question + "?"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try{ String ans = br.readLine(); if(ans != null && ans != "")return ans; System.out.println("Your entry seems empty."); }catch(Exception ex) {} } } private boolean askToPlayAgain(){ while(true){ String ans = getInput("Would you like to play again? (\"YES\" or \"NO\")"); if(ans.equalsIgnoreCase("YES") || ans.equalsIgnoreCase("Y")) return true; if(ans.equalsIgnoreCase("NO") || ans.equalsIgnoreCase("N")) return false; System.out.println("Please respond with \"YES\" or \"NO\""); } } public void Run(){ rnd = new Random(); boolean running = true; boolean gotMaxNumber = false; int maxNumber = 0; int answer = 0; boolean gameOver = false; int tries = 0; System.out.println("*** GUESS A NUMBER : Java ***"); while(running){ while(!gotMaxNumber){ maxNumber = getNumericInput("Please enter the maximum number you wish to use"); if(maxNumber > 0){ gotMaxNumber = true; answer = rnd.nextInt(maxNumber) + 1; gameOver = false; tries = 0; System.out.println("Ok, I am thinking of a number between 1 and " + Integer.toString(maxNumber)); } else System.out.println("The maximum number should be greater than zero."); } int guess = getNumericInput("Guess a number between 1 and " + Integer.toString(maxNumber)); tries++; if(guess > answer) System.out.println("Too high."); if(guess < answer) System.out.println("Too low."); if(guess == answer){ if(tries == 0) System.out.println("You guessed it in 1 try!"); else System.out.println("You guessed it in " + Integer.toString(tries) + " tries!"); gameOver = true; } if(gameOver){ running = askToPlayAgain(); if(running) gotMaxNumber = false; } } System.out.println("Thanks for playing!"); System.out.println("*** GAME OVER ***"); } public static void main(String args[]){ GuessANumber g = new GuessANumber(); g.Run(); } }