Question

Strangest thing. I have this line

int i = Integer.parseInt("3",3);

But everytime i run it, i get a NumberFormatException.forInputString. Why? this is a simple base conversion. What is so special about the int 3 that breaks the conversion?

Was it helpful?

Solution 3

If you want to parse base-10 to base-n String you can use something like :

System.out.println(Integer.toString(3, 2)); // print 11 -> String data type

Code above is to parse 3 in base 10 (integer) as binary (base-2) String.

Following code should parse base-2 String as base-10 integer value :

System.out.println(Integer.parseInt("11", 2)); // print 3 -> base-10 integer

Code above is to parse 11 binary to base-10 integer. Your code have error with this String format, for base-3 the string only consist 0, 1, 2.

Please note the difference how to use both method.

OTHER TIPS

  1. parseInt() expects a String as the first argument.

  2. In base 3 there is no digit "3". Just "0" to "2". A decimal "3" is represented by "10" in base 3.

Integer.parseInt() expects a string to parse, not an integer. You want

int i = Integer.parseInt("3", 3);

You'll also run into the problem that 3 is not a digit in base three. As per the documentation, that will still throw a NumberFormatException.

Any character of the string is not a digit of the specified radix

3 must be a numeric String to parse into an int rather than an int literal:

int i = Integer.parseInt("2", 3);

Furthermore, base-3 numbers cannot contain a 3 digit, as there's only 0, 1 and 2 available. Therefore I used 2 in the example code above.

3 simply does not exist as a digit in base 3... 0, 1, 2, 10, 11, 12, 20, 21, 22, 100

  • Integer.parseInt takes String as a signed decimal integer, and that integer must be less than and not equal radix value (base).

    Integer.parseInt("X",x); //X mustn't contain x.
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top