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))
Ideone
It can convert the String yellow
from base 35, I don't understand why I would get a NumberFormatException
on this String.
To handle this exception, try–catch block can be used. While operating upon strings, there are times when we need to convert a number represented as a string into an integer type. The method generally used to convert String to Integer in Java is parseInt().
The NumberFormatException is an unchecked exception in Java that occurs when an attempt is made to convert a string with an incorrect format to a numeric value. Therefore, this exception is thrown when it is not possible to convert a string to a numeric type (e.g. int, float).
We have used the parseInt method of the Integer class before. The method throws a NumberFormatException if the string it has been given cannot be parsed into an integer.
java.lang.NumberFormatException. Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
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));
Could it be that the number is > Integer.MAX_VALUE
? If I try your code with Long
instead, it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With