Results 1 to 4 of 4
Thread: Scaner NextLine()
- 08-14-2012, 09:54 AM #1
Member
- Join Date
- Mar 2012
- Posts
- 29
- Rep Power
- 0
Scaner NextLine()
Hey could someone explain to me why Info will print/ scan a blank space for Info? I've looked at the scanner class, but still cant seem to get my head around it.(Each token is on its own line)
Thanks.Java Code:Width = scan.nextInt(); System.out.println(Width); Height = scan.nextInt(); System.out.println(Height); Info = scan.nextLine(); System.out.println(Info);
- 08-14-2012, 10:03 AM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,441
- Rep Power
- 16
Re: Scaner NextLine()
I really must store this reply somewhere...
The nextInt() method (and the related next<primitive> ones) will clear the buffer before reading in the int from the console.
In reading in the int they leave behind the new line character(s).
So:
nextInt(); // Read in an int
nextInt(); // clears the new line left behind by the above and then reads in the int
Now, nextLine() is different. It does not clear the buffer.
So:
nextInt(); // read in int, but remember there's still a new line in the buffer.
nextLine(); // Reads in that new line...and nothing else.
So, the simple solution is to call nextLine() after the last nextInt() in order to clear the left over new line in the buffer.Please do not ask for code as refusal often offends.
- 08-14-2012, 10:46 AM #3
Member
- Join Date
- Mar 2012
- Posts
- 29
- Rep Power
- 0
- 08-14-2012, 01:07 PM #4
Moderator
- Join Date
- Apr 2009
- Posts
- 10,441
- Rep Power
- 16
Similar Threads
-
problems with .next() .nextLine(); Loop
By zniightmare in forum New To JavaReplies: 16Last Post: 02-12-2012, 02:32 AM -
nextLine issue
By paul1024 in forum New To JavaReplies: 3Last Post: 03-24-2011, 11:48 PM -
input nextLine error
By scoobyrox in forum New To JavaReplies: 6Last Post: 02-25-2011, 01:08 AM -
input.nextLine();
By Cass29 in forum New To JavaReplies: 3Last Post: 12-21-2009, 07:43 PM -
.nextLine(); only picks up first word
By ethanemc505 in forum New To JavaReplies: 1Last Post: 10-08-2009, 07:30 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks