java.util.InputMismatchException:对于输入字符串:“2147483648”

java.util.InputMismatchException: For input string: "2147483648"

下面是我的代码

public class ExceptionHandling {

    public static void main(String[] args) throws InputMismatchException{
        Scanner sc = new Scanner(System.in);
        int a = 0;
        int b = 0;
        try {
            a = sc.nextInt();
            b = sc.nextInt();

            try {
                int c = a / b;
                System.out.println(b);

            } catch (ArithmeticException e) {
                System.out.println(e);
            }
        } catch (InputMismatchException e) {
            System.out.println(e);
        }

    }

}

我对上述问题的主要查询是,当我将 String 作为输入传递时,我只得到 java.util.InputMismatchException。 但是当我将 2147483648 作为输入传递时,它会给出 java.util.InputMismatchException: For input string: "2147483648" 作为输出。

那么谁能告诉我为什么在那种情况下我得到 For input string: "2147483648"

2147483648 大于原始 Java 整数所能容纳的最大值,即 2147483647。 Java 整数只适合 -2147483648 和 2147483647 [-231 到 231-1 之间的任何值,因为 java int 是一个 32 位整数]。要解决此问题,请使用整数范围内的输入,或者使用更宽的类型,例如 long:

long a = 0;
long b = 0;

try {
    a = sc.nextLong();
    b = sc.nextLong();
    // ...
}
catch (Exception e) { }

My main issue is, while passing "hello" the output is java.util.InputMismatchException. But while passing (2147483648) long in int type the output is= java.util.InputMismatchException: For input string: "2147483648". I want to know why is it printing extra content.

这与您最初提出的问题不同,但我还是会回答。

您获得“额外内容”的原因如下:

java.util.InputMismatchException: For input string: "2147483648"

是不是你打印的异常是这样的:

System.out.println(e);

这会在异常对象上调用 toString() 并打印它。典型异常的 toString() 方法大致等同于:

public String toString() {
    return e.getClass().getName() + ": " + e.getMessage();
}

如果不需要异常名称,只需打印异常消息即可:

System.out.println(e.getMessage());

这将输出:

For input string: "2147483648"

(IMO,这不是您应该向用户显示的那种消息。它没有解释任何内容!)


I want the output to be same for both Hello and 2147483648.

我想会的。对于“你好”,输出将是:

java.util.InputMismatchException: For input string: "Hello"

最后,如果您确实想要一个可理解的错误消息,则需要对代码进行更广泛的修改。不幸的是,nextInt()Integer.parseInt(...) 都没有给出异常消息来解释 为什么 输入字符串不是可接受的 int 值。