将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();
}