NumberFormatException

cs101

#1

Hey guys, I’m a beginner and 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:


When I run the program, there’s a NumberFormatException. I’ve read that this exception occurs when your input is an empty String, null, or a non-numeric String, whereas I entered an integer. I checked my code and I could not find anything wrong, but I’m not sure.
How do I solve this?


#2

Hi @bao :slight_smile:

Let me start this reply of mine with a Disclaimer: I haven’t taken the “CS101: Introduction to Computer Science I” Saylor course yet and I also don’t work at / for Saylor.

I have noticed that, in your “readKeyboard()” Java method (of your “KeyboardReader” class), you correctly start by initializing the String variable “line” to an empty string:

String line ="";

BUT then you don’t assign that variable to anything else, in that method. At the end of the method, you correctly return the line variable:

return line;

… but, as I mentioned above, because you only assigned "line" to an empty string, you are always returning an empty string from that method.

Therefore, I believe that, in that “readKeyboard()” method, where you wrote:

reader.readLine();

… you meant to write the following, instead:

line = reader.readLine();

Am I right? :slight_smile:


#3

Yeah, you’re right :smile:, how did I let that slipped, thanks a lot for taking the time to read my code, you’re the man Ric :kissing_smiling_eyes:


#4

Hi @bao,

You’re most welcome. Thanks for having confirmed that I was right about what I thought to be the issue in your Java programming code.

All the best on your studies! :slight_smile: