java - 为什么在下面的场景中会抛出不同类型的异常?

标签 java double java.util.scanner datainputstream

我正在尝试使用 ScannerDataInputStream 获取用户的输入。这是我正在使用的代码:

场景 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/

相关文章:

swift - 无法将类型 '[String]?' 的值转换为预期的参数类型 'String' Swift

java - 使用 QueryRunner 插入 ArrayList<Object[]>

java - 如何在 Java 中进行非破坏性队列检查

java - 请求 READ_PHONE_STATE 权限时应用程序因 IllegalStateException 崩溃

java - 将字符附加到加载到内存中的文件的最快/最有效的方法是什么?

java - 使用 nextInt 和 nextLine() 时遇到问题

java - 处理控制台输入(换行)

java - 如何在 servlet 中使用 JSONObject 创建多级 JSON 数据

ios - 如何计算小数位数?

java - 这是根据规范进行的 Java 双重解析行为吗?