无法在 Java 中将字符串转换为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3517686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot convert String to Integer in Java
提问by Ding
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:
我有一个字符串 6042076399 它给了我错误:
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?
这不是将字符串转换为整数的正确方法吗?
采纳答案by Steve Pierce
Here's the way I prefer to do it:
这是我更喜欢的方式:
Edit (08/04/2015):
编辑(08/04/2015):
As noted in the comment below, this is actually better done like this:
正如下面的评论中所指出的,实际上这样做更好:
String numStr = "123";
int num = Integer.parseInt(numStr);
回答by codersarepeople
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).
该字符串大于 Integer.MAX_VALUE。您无法解析超出整数范围的内容。(他们上升到 2^31-1,我相信)。
回答by Thomas Owens
That's the correct method, but your value is larger than the maximum size of an int
.
这是正确的方法,但您的值大于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
.
int
可以容纳的最大大小为 2 31- 1,或 2,147,483,647。你的价值是 6,042,076,399。long
如果你想要一个原始类型,你应该考虑将它存储为 a 。long 的最大值明显更大 - 2 63- 1。另一种选择可能是BigInteger
.
回答by Borealid
An Integer
can't hold that value. 6042076399 (413424640921 in decimal) is greater than 2147483647, the maximum an integer can hold.
一个Integer
不能认为值。6042076399(十进制为413424640921)大于2147483647,一个整数可以容纳的最大值。
Try using Long.parseLong
.
尝试使用Long.parseLong
.
回答by Frank
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()
.
除了其他人的回答之外,如果您有一个超过 8 个十六进制数字的字符串(但最多 16 个十六进制数字),您可以将其转换为 long usingLong.parseLong()
而不是 int using Integer.parseInt()
。