好吧,我是一个完全的初学者,如果这对你来说是一个非常愚蠢的问题,我很抱歉。
所以我开始使用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");如果我只得到' if‘条件中的输入,它怎么知道用户是否输入了整数呢?
发布于 2016-06-22 01:02:02
根据Java文档:
如果此扫描器输入中的下一个标记可以解释为int值,则hasNextInt()“返回true。”因此,此方法查看输入,如果输入中的下一项是整数,则返回true。扫描器还没有通过将输入放入变量来“读取”输入。
发布于 2016-06-22 01:03:06
如果您查看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);
}https://stackoverflow.com/questions/37950325
复制相似问题