• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

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

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic