• Post Reply Bookmark Topic Watch Topic
  • New Topic

problems with .next() .nextLine(); Loop  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, Im kinda having a problem with the Scanner class. With this part of my program I ultimately want to be able to enter a company name with spaces allowed and enter data numbers. What problem with this code is that during the second loop the Enter the company name will be skipped. Any help would be awsome!



Running the code....
Enter the name of company number 1: Company One
companyName is-->Company One<---
Enter the rate for Bodily Injury Liability of company number 1: 1
Enter the rate for Property Damage Liability of company number 1: 1
Enter the rate for Uninsured Drivers Coverage of company number 1: 1
Enter the name of company number 2: companyName is--><---
Enter the rate for Bodily Injury Liability of company number 2:

it gets skipped.

MIke
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

What probably happens is that the keyboard.nextDouble() call reads a number, but doesn't process the newline (enter) that you type after entering the number. So the next time the loop is iterated, the newline character will be read and the company name will be empty (keyboard.nextLine() reads the unprocessed newline character and interprets this as an empty line).

What you could do is not use keyboard.nextDouble() to read the numbers, but use keyboard.nextLine() to read a complete line, and then parse that into a Double by calling Double.parseDouble() on the line (string) that was read.
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi there i had kind of the same problem when i was doing my assignment and it seems that what Jesper is saying is right. I used to BufferedReader instead of the Scanner class and the problem was solved...
e.g :


hope this helps.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!