This implementation of the number guess game as a single Java class employing a conventional command-line-interface represents the shortest and simplest of all the implementations. Its interface leaves a lot of room for improvement, but it would be tough to come up with any implementation that was simpler, or more straightforward. In that respect, it is the ideal by which all the other implementations should be judged.
Contents
—[ Return To: “Comparison of Number Guess Implementations” ]—
User Experience
Game In Progress, Bad Input
The bad input was the number "117". There's an indication that the input was wasn't accepted, but no feedback to explain the situation to the user.
A random number between 0 and 100 (inclusive) has been selected. Guess the number: 50 50 is too high. Guess the number: 25 25 is too high. Guess the number: 12 12 is too low. Guess the number: 18 18 is too low. Guess the number: 117 Guess the number:
Game Complete
A random number between 0 and 100 (inclusive) has been selected. Guess the number: 50 50 is too high. Guess the number: 25 25 is too high. Guess the number: 12 12 is too low. Guess the number: 18 18 is too low. Guess the number: 117 Guess the number: 21 21 is too low. Guess the number: 23 23 is too high. Guess the number: 22 Correct! The number was 22. You guessed it in 7 attempts.
Source Code
import java.io.*; public class CLI { public static void main(final String[] args) throws Exception { final BufferedReader In = new BufferedReader(new InputStreamReader(System.in)); final int No = new java.util.Random().nextInt(101); int GuessCount = 0; int Guess; System.out.println("A random number between 0 and 100 (inclusive) has been selected."); do { while (true) { try { System.out.print("Guess the number: "); Guess = Integer.parseInt(In.readLine()); if (Guess >= 0 && Guess <= 100) break; } catch (NumberFormatException e) { System.out.println("That's not a number. Try again."); } } if (Guess < No) System.out.println(Guess + " is too low."); else if (Guess > No) System.out.println(Guess + " is too high."); GuessCount++; } while (Guess != No); System.out.println("Correct! The number was " + No + ". You guessed it in " + GuessCount + " attempts."); } }