Java 如何将String转化为Int及java.lang.NumberFormatException异常处理

来源:互联网 发布:犀牛软件官网 编辑:程序博客网 时间:2024/05/29 18:34

在 Java 中要将 String 类型转化为 int 类型时,需要使用 Integer 类中的 parseInt() 方法或者 valueOf() 方法进行转换.

例1:

1
2
3
4
5
6
String str = "123";
try {
    int a = Integer.parseInt(str);
catch (NumberFormatException e) {
    e.printStackTrace();
}

例2:

1
2
3
4
5
6
String str = "123";
try {
    int b = Integer.valueOf(str).intValue()
catch (NumberFormatException e) {
    e.printStackTrace();
}

在转换过程中需要注意,因为字符串中可能会出现非数字的情况,所以在转换的时候需要捕捉处理异常

如果发现自己转换的字符串都是数字,但还是抛异常,一般是存在空格之类的特殊字符,需要精确提取出字符串中的数字再进行转换,例:'wt.oart.WTPart.343532329',提取字符串要提取从3到9,而不能直接从3开始到结束。

从字符串精确提取数字,参考:http://blog.csdn.net/realroman/article/details/76880223

一般采用正则表达式提取。

Ps:确定自己截取的字符串全是数字;

确定是小于或等于八位。

阅读全文
2 0
原创粉丝点击