Java 中无法将字符串转换为整数
我编写了一个将字符串转换为整数的函数
if ( data != null )
{
int theValue = Integer.parseInt( data.trim(), 16 );
return theValue;
}
else
return null;
我有一个字符串 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)
这不是将字符串转换为整数的正确方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是我更喜欢的方式:
编辑(08/04/2015):
正如下面的评论所述,实际上最好这样做:
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:
Integer
无法保存该值。 6042076399(十进制为 413424640921)大于整数可以容纳的最大值 2147483647。尝试使用Long.parseLong。
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
.这是正确的方法,但您的值大于
int
的最大大小。int
可以容纳的最大大小为 231 - 1,即 2,147,483,647。您的价值是 6,042,076,399。如果您想要原始类型,您应该考虑将其存储为long
。 long 的最大值明显更大 - 263 - 1。另一个选项可能是BigInteger
。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 along
if you want a primitive type. The maximum value of a long is significantly larger - 263 - 1. Another option might beBigInteger
.该字符串大于 Integer.MAX_VALUE。您无法解析超出整数范围的内容。 (我相信它们最多可达 2^31-1)。
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).
除了其他人的回答之外,如果您的字符串超过 8 个十六进制数字(但最多 16 个十六进制数字),您可以使用
Long.parseLong()
将其转换为 long,而不是使用Integer.parseInt()
转换为 int。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 usingInteger.parseInt()
.