Reputation: 135
Input
So, I know that nextLine()
reads the whole line and moves the cursor to the next line and nextFoo()
reads only up till it encounters a space and keeps the cursor there (doesn't move it to a new line).
So initially I tried this:-
int N = Integer.parseInt(in.nextLine()); //reading the whole line and parsing it to Integer. The cursor pointer is moved to the next line
while(--N>=0){
p = in.nextInt(); q = in.nextInt(); //reading the two space seperated integers
in.nextLine();//to move the cursor to the next line
}
But this wasn't working properly, couldn't read the last p and q I was inputting.
Changed it to:
int N = in.nextInt();
while(--N>=0){
p = in.nextInt(); q = in.nextInt();
}
And it is working fine. How is nextInt()
going to the next line? All .nextFoo()
and .next()
except .nextLine()
read only up till there is a space and keep the cursor pointer there, right? How is this going to the newline then?
Upvotes: 0
Views: 2221
Reputation: 41223
From the Scanner
Javadoc:
The
next()
andhasNext()
methods and their primitive-type companion methods (such asnextInt()
andhasNextInt()
) first skip any input that matches the delimiter pattern, and then attempt to return the next token.
So the cursor is before the newline, then when you call nextInt()
, skips through the newline and any other whitespace, before consuming the number.
Your code containing nextLine()
will work, as long as your input file ends in a newline. It's conventional to end text files with a newline character -- many editors will either force you to have one, or display a warning if it's missing.
Upvotes: 1