【发布时间】: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