Results 1 to 4 of 4
Thread: Scanner for String in for loop
- 11-24-2012, 04:16 PM #1
Member
- Join Date
- Oct 2012
- Location
- Trinidad
- Posts
- 4
- Rep Power
- 0
Scanner for String in for loop
I need to read the name of a person in a program and then a number amount for sales.
Essentially I create a scanner object "read" and do this.
Name = read.nextLine();
sales = read.nextDouble();
(I removed most of the other code to avoid confusion). This works fine at first but im running in a for loop which means it then tries to repeat the code. When it tries again it skips the name entry. I know this is something to do with a nextline glitch that happens when you read.nextLine after a double.
I would usually do this
Name = read.nextLine();
Name = read.nextLine();
That usually solves the problem in procedural but if I do that in this program I have to enter the first person's name twice. Is there a way around this that I can read a string and a double one after the other?
-
Re: Scanner for String in for loop
One problem you may be running into is that Scanner#nextDouble() (and nextInt(), next(),...) do not handle the end of line (EOL) token, and so this token is being read by your next call to nextLine(), where you're trying to read in the next name. A solution is to call nextLine() when you need to handle that token. For instance:
Note that for similar problems, you'll want to post some of the data file so we can see how it is formatted as this can change everything.Java Code:name = read.nextLine(); sales = read.nextDouble(); read.nextLine(); // **** add this to handle the EOL token ****
- 11-24-2012, 04:41 PM #3
Member
- Join Date
- Oct 2012
- Location
- Trinidad
- Posts
- 4
- Rep Power
- 0
Re: Scanner for String in for loop
Thank you very much that helped a lot program works perfectly now :)
-
Re: Scanner for String in for loop
Glad it works!
Similar Threads
-
Scanner, while loop and sorting arrays/string?
By RSYR in forum New To JavaReplies: 10Last Post: 04-20-2011, 06:13 PM -
Scanner class in my for loop
By Mode in forum New To JavaReplies: 1Last Post: 12-20-2010, 09:48 AM -
Scanner Loop
By Phenomena in forum New To JavaReplies: 2Last Post: 04-01-2010, 06:47 PM -
Scanner-While Loop
By hyunski in forum New To JavaReplies: 2Last Post: 03-12-2009, 02:15 AM -
Using java.util.Scanner to search for a String in a String
By Java Tip in forum Java TipReplies: 0Last Post: 11-20-2007, 04:59 PM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks