将String字符串转化为int

将String字符串转化为int类型需要使用 Integer 类中的 parseInt() 方法或者 valueOf() 方法进行转换!

1、

String str = "123456";
//str --> int
int i1 = Integer.parseInt(str);
System.out.println(i1);

2、

String str = "123456";
int i2 = Integer.valueOf(str).intValue();
System.out.println(i2);

3、

//此方法只适合学习时用
//str --> Integer --> int
String str = "123456";
Integer ii = new Integer(str);
int i2 = ii.intValue();
System.out.println(i2);

注意:在转换过程中,输入字符串时,有非数字字符时,无法转换,需要抛出异常!

//抛出异常
try {
    //转换的代码
} catch (NumberFormatException e) {
    e.printStackTrace();
}
发布了87 篇原创文章 · 获赞 143 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44170221/article/details/104639146