【问题标题】:why parseInt here causes NumberFormatException inside the for loop at index i=4 [duplicate]为什么 parseInt 会在索引 i=4 处的 for 循环内导致 NumberFormatException [重复]
【发布时间】:2021-06-21 21:44:46
【问题描述】:

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

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)

【问题讨论】:

  • 请仔细查看您的输出(以及下面答案中的 cmets)-“40 到基数 8 = 32”不是对 parseInt 所做的正确解释。您实际上期望从中获得什么价值? Integer.parseInt("40", 8)?
  • 这似乎只是一个措辞问题,而不是对功能的误解。 “40 in base 8 = 32”更惯用; “以 8 为底的 40 = 以 10 为底的 32”会更清楚。 “以 X 为基数”附加到 X 中的数字 (c.f. "20 hex = 32")。

标签: java loops for-loop numberformatexception parseint


【解决方案1】:

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

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

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

【讨论】:

  • 当我使用 50 或 30 而不是 40 时,我遇到了同样的问题,50 在索引 5 处停止,30 在索引 3 处停止,但为什么它只接受大于 4 的索引
  • 如何在不尝试 catch 块的情况下解决此问题,我正在寻找不同的解决方案,以免发生错误
  • @coderscommunity 字符串 "40" 仅对基数 5 到 36 有效。要修复错误,请不要使用基数 36 调用。
  • 但是为什么我必须检查 36,如果循环从索引 10 下降到 5
  • 您似乎将 parseInt(N, b) 误解为“以 b 为基数表示十进制数 N”,实际上它的意思是“将数字 N 表示为以 b 为基数的字符串并返回它是一个(十进制)数字”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多