I feel like I must be missing something simple, but I am getting a NumberFormatException on the following code:
System.out.println(Integer.parseInt("howareyou",35)) It can convert the String yellow from base 35, I don't understand why I would get a NumberFormatException on this String.
7 Answers
Because the result will get greater than Integer.MAX_VALUE
Try this
System.out.println(Integer.parseInt("yellow", 35)); System.out.println(Long.parseLong("howareyou", 35)); and for
Long.parseLong("abcdefghijklmno",25) you need BigInteger
Try this and you will see why
System.out.println(Long.MAX_VALUE); System.out.println(new BigInteger("abcdefghijklmno",25)); 2Could it be that the number is > Integer.MAX_VALUE? If I try your code with Long instead, it works.
The number is getting bigger than Integer.MAX_VALUE
Try this:
System.out.println(Integer.parseInt("yellow", 35)); System.out.println(Long.parseLong("howareyou", 35)); As seen in René Link comments you are looking for something like this using a BigInteger:
BigInteger big=new BigInteger("abcdefghijklmno", 25); Something like this:
System.out.println(Long.MAX_VALUE); System.out.println(new BigInteger("abcdefghijklmno",25)); From the JavaDocs:
An exception of type
NumberFormatExceptionis thrown if any of the following situations occurs:
- The first argument is
nullor is a string of length zero. FALSE: "howareyou" is notnulland over 0 length- The radix is either smaller than
Character.MIN_RADIXor larger thanCharacter.MAX_RADIX. FALSE: 35 is in range [2,36]- Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1. FALSE: all characters of "howareyou" are in radix range [0,'y']
- ==> The value represented by the string is not a value of type
int. TRUE: The reason for the exception. The value is too large for anint.
Either Long or BigInteger should be used
As you can see, you're running out of space in your Integer. By swapping it out for a Long, you get the desired result. Here is the IDEOne Link to the working code.
Code
System.out.println(Integer.parseInt("YELLOW",35)); System.out.println(Long.parseLong("HOWAREYOU",35)); The previous answers of parseLong would be correct, but sometime that is also not large enough so the other option would to use a BigInteger.
Long.parseLong("howareyou", 35) new BigInteger("howareyou", 35) The number produced is too large for a Java Integer, use a Long.