Cannot convert String to Integer in Java [duplicate]

二次信任 提交于 2019-12-01 15:29:15

问题


I have written a function to convert string to integer

   if ( data != null )
   {
        int theValue = Integer.parseInt( data.trim(), 16 );
        return theValue;
   }
   else
       return null;

I have a string which is 6042076399 and it gave me errors:

Exception in thread "main" java.lang.NumberFormatException: For input string: "6042076399"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:461)

Is this not the correct way to convert string to integer?


回答1:


Here's the way I prefer to do it:

Edit (08/04/2015):

As noted in the comment below, this is actually better done like this:

String numStr = "123";
int num = Integer.parseInt(numStr);



回答2:


An Integer can't hold that value. 6042076399 (413424640921 in decimal) is greater than 2147483647, the maximum an integer can hold.

Try using Long.parseLong.




回答3:


That's the correct method, but your value is larger than the maximum size of an int.

The maximum size an int can hold is 231 - 1, or 2,147,483,647. Your value is 6,042,076,399. You should look at storing it as a long if you want a primitive type. The maximum value of a long is significantly larger - 263 - 1. Another option might be BigInteger.




回答4:


That string is greater than Integer.MAX_VALUE. You can't parse something that is out of range of integers. (they go up to 2^31-1, I believe).




回答5:


In addition to what the others answered, if you have a string of more than 8 hexadecimal digits (but up to 16 hexadecimal digits), you could convert it to a long using Long.parseLong() instead of to an int using Integer.parseInt().



来源:https://stackoverflow.com/questions/3517686/cannot-convert-string-to-integer-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!