Integer.parseInt(String str) java.lang.NumberFormatException: Errors(Integer.parseInt(String str) java.lang.NumberFormatException: 错误)
问题描述
I keep getting number format expectations, even though I'm trimming the strings and they don't contain non numerical characters bizarrely it works for some numbers and not others. Below is an example of a string I get number format exception for. Also, any string starting with 0 e.g "0208405223", is returned 208405223, there's no zero anymore is that supposed to happen?
String n="3020857508";
Integer a = Integer.parseInt(n.trim());
System.out.println(a);
This is the exception:
Exception in thread "main" java.lang.NumberFormatException: For input string: "3020857508"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:583)
at java.lang.Integer.parseInt(Integer.java:615)
at JavaBeans.Main.main(Main.java:15)
It's because 3020857508
exceeds Integer.MAX_VALUE
. You should use long
to convert the string to number.
java> String n="3020857508";
//=> java.lang.String n = "3020857508"
java> Integer a = Integer.parseInt(n.trim());
//=> java.lang.NumberFormatException: For input string: "3020857508"
java> Integer.MAX_VALUE
//=> java.lang.Integer res2 = 2147483647
java> Long a = Long.parseLong(n.trim());
//=>java.lang.Long a = 3020857508
The above is javarepl output.
If you are using JDK9 or above, you can see the same result in jshell.
jshell> String n="3020857508"
n ==> "3020857508"
jshell> Integer a = Integer.parseInt(n.trim())
| Exception java.lang.NumberFormatException: For input string: "3020857508"
| at NumberFormatException.forInputString (NumberFormatException.java:65)
| at Integer.parseInt (Integer.java:652)
| at Integer.parseInt (Integer.java:770)
| at (#2:1)
jshell> Integer.MAX_VALUE
$3 ==> 2147483647
jshell> Long a = Long.parseLong(n.trim());
a ==> 3020857508
这篇关于Integer.parseInt(String str) java.lang.NumberFormatException: 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Integer.parseInt(String str) java.lang.NumberFormatException: 错误


基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01