I’m doing this exercise where I need to design a program that will generate a random number between 1 and 100 and then let the user guess the number and tell them whether the guess is too high or too low. Here’s the code:
The Evaluator class:
import java.io.*; public class Evaluator { private KeyboardReader reader = new KeyboardReader(); public String evaluate(int guess, int secretNum) { if(guess > secretNum) return "Too high"; else return "Too low"; } // evaluate() public void run() { int secretNum = 1 + (int)(Math.random()*100); reader.prompt("What's your guess? -> "); guess = reader.getKbInt(); reader.display(evaluate(guess, secretNum)); } // run() public static void main(String args[]) { Evaluator app = new Evaluator(); app.run(); } // main }
The KeyboardReader class
import java.io.*; public class KeyboardReader { private BufferedReader reader; public KeyboardReader() { reader = new BufferedReader(new InputStreamReader(System.in)); } // KeyboardReader private String readKeyboard() { String line = ""; try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return line; } // readKeyboard() public String getKbInput() { return readKeyboard(); } public int getKbInt() { return Integer.parseInt(readKeyboard()); } public double getKbDouble() { return Double.parseDouble(readKeyboard()); } public void prompt(String s) { System.out.print(s); } public void display(String s) { System.out.print(s); } } // KeyboardReader
I entered an integer and a NumberFormatException was thrown:
C:\LearnJava>java Evaluator
What's your guess? -> 4
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(Num berFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:776)
at KeyboardReader.getKbInt(KeyboardReader.java:28)
at Evaluator.run(Evaluator.java:21)
at Evaluator.main(Evaluator.java:28)
How do I fix this?