首页 > 解决方案 > 为什么这里的 parseInt 会在索引 i=4 处的 for 循环内导致 NumberFormatException

问题描述

我不知道原因,为什么 i=4 导致 Numberformatexception,我可以使用 try 和 catch 来处理 Numberformatexception,但我实际上不知道这个错误的原因,以及如何在不使用 try,catch 的情况下修复它阻止,有人可以帮忙吗?

public class Main {
public static void main(String[] args) {  
   int i;     
   int base = 0; 
   for (base = 10; base >= 2; --base) {   
         i = Integer.parseInt("40", base);   
         System.out.println("40 to the Base " + base + " = " + i); 
       }  
  }
}

输出:

40 to the Base 10 = 40 // (10^0 * 0) + (10^1 * 4) 
40 to the Base 9 = 36 // (9^0 * 0) + (9^1 * 4) 
40 to the Base 8 = 32
40 to the Base 7 = 28
40 to the Base 6 = 24
40 to the Base 5 = 20
Exception in thread "main" java.lang.NumberFormatException: For input string: "40"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)

标签: javaloopsfor-loopnumberformatexceptionparseint

解决方案


40 不是有效的以 2、3 或 4 为基数的数字。

只需比较说八进制(以 8 为底) - 计数为 0、1、2、3、4、5、6、7、10、11 ... - 8 不是有效的八进制数字。4 仅对基数 5 及以上有效。

parseInt()接受一个字符串和该字符串所在的基数并返回整数值。例如parseInt("10", 10) = 10但是parseInt("10", 8) = 8。您的问题是“40”对基数 2、3 或 4 无效。同样,50 对基数 2..5 无效。


推荐阅读