scanner.nextLine() 和 scanner.next(); 的区别

查看 scanner.nextLine() 的源码,可以发现是一次性读完的

/**
* 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.
*
* <p>Since this method continues to search through the input looking
* for a line separator, it may buffer all of the input searching for
* the line to skip if no line separators are present.
*
* @return the line that was skipped
* @throws NoSuchElementException if no line was found
* @throws IllegalStateException if this scanner is closed
*/
public String nextLine() {
if (hasNextPattern == linePattern())
return getCachedResult();
clearCaches();

String result = findWithinHorizon(linePattern, 0);
if (result == null)
throw new NoSuchElementException("No line found");
MatchResult mr = this.match();
String lineSep = mr.group(1);
if (lineSep != null)
result = result.substring(0, result.length() - lineSep.length());
if (result == null)
throw new NoSuchElementException();
else
return result;
}

查看 scanner.next() ,可以发现是以空格为划分读的。

/**
* 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 {@link #hasNext} returned
* <code>true</code>.
*
* @return the next token
* @throws NoSuchElementException if no more tokens are available
* @throws IllegalStateException if this scanner is closed
* @see java.util.Iterator
*/
public String next() {
ensureOpen();
clearCaches();

while (true) {
String token = getCompleteTokenInBuffer(null);
if (token != null) {
matchValid = true;
skipped = false;
return token;
}
if (needInput)
readInput();
else
throwFor();
}
}

scanner.nextLine()和scanner.next();的区别_sed

scanner.nextLine()和scanner.next();的区别_sed_02