Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer.parseInt number format exception?

Tags:

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.

like image 822
Danny Avatar asked Nov 26 '13 14:11

Danny


People also ask

How do I resolve number format exception?

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().

What is a number format exception?

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).

What exception does integer parseInt throw?

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.

What does java Lang NumberFormatException mean?

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.


2 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)); 
like image 114
René Link Avatar answered Oct 08 '22 18:10

René Link


Could it be that the number is > Integer.MAX_VALUE? If I try your code with Long instead, it works.

like image 29
Blub Avatar answered Oct 08 '22 19:10

Blub