简体   繁体   中英

Integer.parseInt number format exception?

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.

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

From the JavaDocs:

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero. FALSE: "howareyou" is not null and over 0 length
  • The radix is either smaller than Character.MIN_RADIX or larger than Character.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 '-' ('\-') or plus sign '+' ('\+') 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 an int .

Either Long or BigInteger should be used

Could 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));

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 .

System.out.println(Integer.parseInt("YELLOW",35));
System.out.println(Long.parseLong("HOWAREYOU",35));

生成的数字对于Java Integer而言太大,请使用Long。

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM