-4

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)
  • Please look carefully at your output (and comments on the answer below) - "40 to the base 8 = 32" is not a correct interpretation of what parseInt does. What value do you actually expect from e.g. `Integer.parseInt("40", 8)`? – Simon Bowly Jun 21 '21 at 23:22
  • It seems like just a wording issue rather than a misunderstanding of function. "40 in base 8 = 32" is more idiomatic; "40 in base 8 = 32 in base 10" would be clearer. The "in base X" attaches to the number that's in that X (*c.f.* "20 hex = 32"). – iggy Jun 22 '21 at 00:48

1 Answers1

2

40 is not a valid base 2, 3 or 4 number.

Just compare to say octal (base 8) - counting is 0, 1, 2, 3, 4, 5, 6, 7, 10, 11 ... - 8 is not a valid octal digit. 4 is only valid for base 5 and above.

parseInt() takes a string and the base that string is in and returns the integer value. e.g. parseInt("10", 10) = 10 but parseInt("10", 8) = 8. Your problem is that "40" is not valid for base 2, 3 or 4. Likewise 50 is not valid for bases 2..5.

John3136
  • 28,809
  • 4
  • 51
  • 69
  • when i used 50 or 30 instead of 40, i get the same problem , with 50 stop at index 5 and with 30 at index 3, but why it accepts only the indexes, that bigger than 4 – coders community Jun 21 '21 at 22:10
  • how can i fix this problem without try catch Block, I 'm looking for different solution, so that no error occur – coders community Jun 21 '21 at 22:21
  • @coderscommunity The string `"40"` is only valid for bases 5 to 36. To fix the error, don't call with a base < 5 or a base > 36. – Andreas Jun 21 '21 at 22:24
  • But why i have to check 36, if the loop goes descending from index 10 to 5 – coders community Jun 21 '21 at 22:30
  • 2
    It seems that you are misinterpreting parseInt(N, b) as "express the decimal number N in base b" where in fact it means "take the number N expressed as a string in base b and return it as a (decimal) number". – Simon Bowly Jun 21 '21 at 22:36