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?
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.
The nextLine() method of the java. util. Scanner class scans from the current position until it finds a line separator delimiter. The method returns the String from the current position to the end of the line.
next() method finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
nextLine() method advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With