gpt4 book ai didi

java - 数字格式和输入不匹配异常有何不同

转载 作者:行者123 更新时间:2023-12-02 06:45:33 25 4
gpt4 key购买 nike

当在 Integer 类构造函数中传递字符值而不是整数值时,以下代码将引发 NumberFormatException

class Wrap
{
public static void main(String...args)
{
Integer j=new Integer("s");
System.out.println(j);
}
}

当用户输入字符值而不是整数值时,以下代码将抛出 InputMismatchException

import java.util.Scanner;

class User
{
public static void main(String...args)
{
Scanner obj=new Scanner(System.in);
int i=obj.nextInt();
int j=obj.nextInt();
System.out.println("sum of numbers input by user");
System.out.println(i+j);
}
}

这两个异常似乎都是在相同的场景中抛出的,那么它们有何不同?

最佳答案

让我们看看这两个异常类的规范:

InputMismatchException 特定于扫描仪。它表示无效类型,不一定是无效数字。 NumberFormatException 特定于尝试将非数字字符串转换为数字。

public class InputMismatchException extends NoSuchElementException

Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

public class NumberFormatException extends IllegalArgumentException

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

关于java - 数字格式和输入不匹配异常有何不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18670128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com