What's the difference between next() and nextLine() methods from Scanner class?
What is the main difference between next()
and nextLine()
?
My main goal is to read the all text using a Scanner
which may be "connected" to any source (file for example).
Which one should I choose and why?
I always prefer to read input using nextLine()
and then parse the string.
Using next()
will only return what comes before the delimiter (defaults to whitespace). nextLine()
automatically moves the scanner down after returning the current line.
A useful tool for parsing data from nextLine()
would be str.split("\\s+")
.
String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces
For more information regarding the Scanner class or String class refer to the following links.
Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
next()
can read the input only till the space. It can't read two words separated by a space. Also, next()
places the cursor in the same line after reading the input.
nextLine()
reads input including space between the words (that is, it reads till the end of line \n
). Once the input is read, nextLine()
positions the cursor in the next line.
For reading the entire line you can use nextLine()
.
From JavaDoc:
- A
Scanner
breaks its input into tokens using a delimiter pattern, which by default matches whitespace.next()
: Finds and returns the next complete token from this scanner.nextLine()
: Advances this scanner past the current line and returns the input that was skipped.
So in case of "small example<eol>text"
next()
should return "small" and nextLine()
should return "small example"