Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 233
AnnieOK Avatar asked Mar 17 '14 15:03

AnnieOK


People also ask

What is the difference between next () and nextLine () method of scanner class?

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.

What is the use of nextLine () method in scanner class?

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.

What is next () method from scanner?

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.

What does nextLine () do?

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.


1 Answers

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

like image 187
Tristan Avatar answered Sep 17 '22 18:09

Tristan