I don't know the reason, why i=4 cause Numberformatexception, I can use try and catch to handle the Numberformatexception, but i actually don't know the reason for this mistake, and how can i fix it without using try,catch block ,can someone help, please.
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);
}
}
}
Output:
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)