通过DEBUG追踪了下。Scanner最后是调用 public String next(Pattern pattern) 方法获取一个String对象,通过Pattern表示要获取对象的类型。代码如下
public String next(Pattern pattern) {
ensureOpen();
if (pattern == null)
throw new NullPointerException();
// Did we already find this pattern?
if (hasNextPattern == pattern)
return getCachedResult();
clearCaches();
// Search for the pattern
while (true) {
String token = getCompleteTokenInBuffer(pattern);//尝试获取符合类型的结果
if (token != null) {
matchValid = true;
skipped = false;
return token;
}
if (needInput) //是否需要input数据
readInput();
else
throwFor();
}
}
问题就出在getCompleteTokenInBuffer(pattern)和`if (needInput)readInput();`首先初次尝试失败后,会判断是否需要input数据,此时你还没有输入数据,因此通过readInput();得到数据的数据,并把needInput设置为了false然后再次调用getCompleteTokenInBuffer(pattern);然而调试里面的代码发现,当pattern指定的类型与你实际输入的类型不匹配时,并不会讲needInput设置为false,查看该方法的说明:
/*
* Returns a "complete token" that matches the specified pattern
*
* A token is complete if surrounded by delims; a partial token
* is prefixed by delims but not postfixed by them
*
* The position is advanced to the end of that complete token
*
* Pattern == null means accept any token at all
*
* Triple return:
* 1. valid string means it was found
* 2. null with needInput=false means we won't ever find it
* 3. null with needInput=true means try again after readInput (意味着这是readInput后的又一次尝试)
*/
private String getCompleteTokenInBuffer(Pattern pattern) {
/*
...
*/
}
因此,当你循环调用next()方法时,只会不停的尝试将你上次输入的数据中获取你想要的int类型数据。