• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Reading scanner input from the keyboard

 
Ranch Hand
Posts: 42
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

 
Ranch Hand
Posts: 570
3
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to add   after line  
 
Saloon Keeper
Posts: 10781
86
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic