• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading scanner input from the keyboard  RSS feed

 
ras oscar
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Below is a code fragment that has me puzzled. The source compiles fine but complains of a run time error on line 23. What confuses me is that the method for retrieving an integer is exactly the same as used on line 16. The console reads:

enter first integer
22
Enter Operation
-
Enter Second Integer
Exception in thread "main" java.lang.NumberFormatException: For input string: ""

at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInteger(Unknown Source)
at Java.lang.Integer.parseInteger(unknown Source)
at Calculator.main(Calculator.java:24)

note: the line number in the error message is one line off because I cleaned up my code at posting by moving some code to a separate line.

 
John Joe
Ranch Hand
Posts: 439
3
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to add  after line 
 
Carey Brown
Saloon Keeper
Posts: 3328
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

On line 21 you call next(). This has the side effect of leaving a new-line character in the input queue. When you call nextLine() on line 23 it sees that pending new-line as a indication that you have a complete line but will only return an empty string.

Two ways to fix this:
Change your call from next() to nextLine().
Add a call to nextLine() after line 21. This will flush out the pending new-line.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!