本文介紹了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
這篇關(guān)于Integer.parseInt(String str) java.lang.NumberFormatException: 錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!