我正在尝试使用 Scanner
和 DataInputStream
获取用户的输入。这是我正在使用的代码:
场景 1:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
double d1 = scanner.nextDouble();
场景 2:
DataInputStream din = new DataInputStream(System.in);
System.out.print("Enter a number: ");
double d2 = Double.parseDouble(in.readLine());
当提供一些字符(如 abc)输入时:
在场景 1 中,我收到 InputMismatchException
。
在场景 2 中,我收到 NumberFormatException
。
为什么Scanner
抛出不同的异常?有人可以澄清一下吗?
最佳答案
Scanner.nextDouble()
的 JavaDoc 说:
Scans the next token of the input as a double. This method will throw InputMismatchException if the next token cannot be translated into a valid double value. If the translation is successful, the scanner advances past the input that matched.
Returns:
The double scanned from the input
Throws:
InputMismatchException - if the next token does not match the Float regular expression, or is out of range
NoSuchElementException - if the input is exhausted
IllegalStateException - if this scanner is closed
检查您的Scanner.class
来源:
public double nextDouble() {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Double)) {
double val = ((Double)typeCache).doubleValue();
useTypeCache();
return val;
}
setRadix(10);
clearCaches();
// Search for next float
try {
return Double.parseDouble(processFloatToken(next(floatPattern())));
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
尝试解析时,如果 Double.parseDouble()
抛出 NumberFormatException
(根据您的场景 2),则 Scanner.nextDouble()
抛出 InputMismatchException
(根据您的场景 1)。
关于java - 为什么在下面的场景中会抛出不同类型的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23290341/