Integer.parseInt("9646324351")报NumberFormatException

原因

NumberFormatException是一个Java异常,表示在将字符串转换为整数时发生错误。在这种情况下,Integer.parseInt("9646324351")导致NumberFormatException的原因是结果超出了Integer的取值范围。

在Java中,Integer.parseInt()方法将字符串转换为int类型的整数。然而,int数据类型的范围是从-2,147,483,648到2,147,483,647(包括边界值)。如果要转换的字符串表示的数字超过了这个范围,就会抛出NumberFormatException异常。

对于字符串"9646324351",其表示的数字大于Integer的最大值,所以无法将其转换为int类型的整数,从而触发了NumberFormatException异常。

如果需要处理超出Integer范围的整数,可以考虑使用long数据类型或者BigInteger类来进行转换和操作。

解决方案

先转换为long类型,再与Integer的最大取值和最小取值进行比较

long number = Long.parseLong(numberString);
if (number > Integer.MAX_VALUE || number < Integer.MIN_VALUE) {
    // 超过int的取值范围
    System.out.println("数字超过了int的最大取值范围");
} else {
    // 在int的取值范围内
    int intValue = (int) number;
    System.out.println("转换后的整数值:" + intValue);
}

posted @ 2023-07-10 13:51  进击的小蔡鸟  阅读(383)  评论(0编辑  收藏  举报