numberformatexception表示数字格式化异常,需要查看字符串里面夹杂着string或者其他类型,需要注意文本里面的内容必须是数字形式的字符串。
本教程操作环境:windows7系统、dell g3电脑。
今天出现了个数字转换异常,处理好后稍微总结了几个出现情景。
e/adroidrutime:致命异常:java.lang.numberformatexception: invalid int: 0
java.lang.numberformatexception 数字格式异常。当试图将一个string转换为指定的数字类型,而该字符串确不满足数字类型要求的格式时,抛出该异常.
invalid int: 0 提示 把 0 转换成数字类型时出错了.
具体是哪个类的哪个方法的哪一行的错误了,看下面错误堆栈,at com.example.myclock.timerview$5.ontextchanged(timerview.java:95) 在com.example.myclock.timerview 类的ontextchanged方法里,imerview.java的第95行出错了
. ------原因分析--------------------
0 在0后面有空格,在字符串转换成数字时应该去除空格。
------解决方案--------------------
如: int vale=integer.parseint(s.tostring().trim()); // tostring()是转化为字符串的方法 trim()是去字符串两边空格的方法。
其他抛出numberformatexception情况:
情况一,超出转换数值类型范围:
用integer.parseint()转换字符时抛出numberformatexception异常,把字符改短一点又没事 string line3[1]= 8613719716 ; int int1=java.lang.integer.parseint(line3[1]);
以上是程序中的一小段,但是在运行的过程中总是抛出异常 exception in thread main java.lang.numberformatexception: for input string: 8613719716
------原因分析--------------------
int类型存储范围是-2,147,483,648 --2,147,483,647。用system.out.println(integer.max_value);输出的是2147483647。而你的 string line3[1]= 8613719716 ;超过了这个最大的值。
------解决方案--------------------
8613719716 根本无法直接使用int表示的,只能用long , 如果更大了就得用到biginteger 。 long.parselong(string)。
参考:http://www.myexception.cn/j2se/numberformatexception.html
情况二,转换值类型没有考虑值为空的状况:
在android中这个序列是否正确,我打算把得到的edittext中的值转换为整数.
starttime_hour_int=integer.parseint(starttime_hour_edittext.geteditabletext().tostring());
logcat 出现了如下错误. 05-12 10:26:35.536: error/androidruntime(293): java.lang.numberformatexception: unable to parse '' as integer
. ------原因分析--------------------
如果textbox starttime_hour_edittext 为空, integer.parseint就会试图把 转换成 integer。这就是numberformatexception出现的原因。所以在转换为int类型前需要判断 textbox starttime_hour_edittext中是否为空。
------解决方案--------------------
在使用 starttime_hour_int=integer.parseint(starttime_hour_edittext.geteditabletext().tostring());之前
判断条件:
if(!starttime_hour_edittext.gettext().tostring().equalsignorecase("")) {starttime_hour_int=integer.parseint(starttime_hour_edittext.geteditabletext().tostring());}
情况三,由于进制不同:
题主要做一个进制转换.并且限定范围为 30位的数 (1073741823) 或者(0111111111111111111111111111111). 问题出现在试图转换 111111111111111111111111111111的时候,出现 numberformatexception.
此代码是检查输入如果是二进制就转换为int型数值
if (checknumber(input)) { try { number = integer.parseint(input); } catch (numberformatexception ex) { log(ex.getmessage()); } } else { todecimal(); }
这是检查 string的布尔返回值方法的代码.
private static boolean checknumber(string input) { for (char c : input.tochararray()) { if (!character.isdigit(c)) { return false; } } return true;}
出现异常:
java.lang.numberformatexception: for input string: "111111111111111111111111111111"
------原因分析--------------------
因为 integer.parseint(string) 默认是十进制.
所以需要使用 integer.parseint(string, int) 并且指定要转换的n进制的数字的n。比如二进制是2.
------解决方案--------------------
int value = integer.parseint(input, 2);
更多编程相关知识,请访问:编程入门!!
以上就是numberformatexception是什么异常的详细内容。