扫描仪类方法
问题描述:
好吧,所以我是一个完整的初学者,如果这对你来说真是一个愚蠢的问题,我很抱歉。扫描仪类方法
所以我开始使用Scanner类,而对我而言似乎有些奇怪。
例如,这行代码:
Scanner scan = new Scanner(System.in);
System.out.print("Write string: ");
if(scan.hasNextInt()){
int x = scan.nextInt();
}
else
System.out.println("Only integers allowed");
它是如何知道用户是否输入了一个整数或没有,如果我只得到了“如果”条件内的输入?
答
根据Java文档:“如果在此扫描器输入信息的下一个标记可以解释为一个int值返回true”
hasNextInt()所以这个方法查看输入,如果下一个东西是一个整数,它返回true。扫描仪还没有通过将其输入到变量中来“读取”输入。
+0
但基数是什么意思?要读取的字符数量?或者是整行上的字符总数? – Azurespot
答
如果你看一下实际执行hasNextInt
,然后就可以看到它是如何知道:
/**
* Returns true if the next token in this scanner's input can be
* interpreted as an int value in the specified radix using the
* {@link #nextInt} method. The scanner does not advance past any input.
*
* @param radix the radix used to interpret the token as an int value
* @return true if and only if this scanner's next token is a valid
* int value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextInt(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
注意:hasNextInt()
只是调用hasNextInt(int radix)
,其中defaultRadix = 10
public boolean hasNextInt() {
return hasNextInt(defaultRadix);
}
@Okx ,哦,它工作得很好。 – Asker
由于您创建的每个问题都以标题中的“Java”开头:[停止这样做](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles)。 – Tom