现在承认,这只是 Sun 实现,但下面是 nextInt(int radix) 实现。
请注意,它使用特殊模式 ( integerPattern()
)。这意味着如果您使用next()
,您将使用您的默认模式。现在,如果您刚刚制作了 a new Scanner()
,您将使用典型的空白模式。但是,如果你使用不同的模式,你就不能确定你会拿起一个词。你可能在接电话什么的。
在一般情况下,我强烈推荐nextInt()
,因为它为您提供了抽象,减少了出错的可能性,并在出现问题时提供了更多信息。
闲暇时阅读:
public int nextInt(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Integer)
&& this.radix == radix) {
int val = ((Integer)typeCache).intValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next int
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}