如何在Java中将字符串转换为int
时间:2020-01-09 10:35:29 来源:igfitidea点击:
要将Java中的String转换为int,可以使用以下选项之一
- Integer.parseInt(String str)方法,将传递的String作为int返回。
- Integer.valueOf(String str)方法,该方法将传递的String作为Integer返回。
Java示例,使用Integer.parseInt()将String转换为int
public class StringToInt {
public static void main(String[] args) {
String str = "12";
try{
int num = Integer.parseInt(str);
System.out.println("value - " + num);
// can be used in arithmetic operations now
System.out.println(num+"/3 = " + num/3);
}catch(NumberFormatException exp){
System.out.println("Error in conversion " + exp.getMessage());
}
}
}
输出:
value - 12 12/3 = 4
Java示例,使用Integer.valueOf将String转换为int
public class StringToInt {
public static void main(String[] args) {
String str = "12";
try{
Integer num = Integer.valueOf(str);
System.out.println("value - " + num);
// can be used in arithmetic operations now
System.out.println(num+"/3 = " + num/3);
}catch(NumberFormatException exp){
System.out.println("Error in conversion " + exp.getMessage());
}
}
}
输出:
value - 12 12/3 = 4
在此示例中,我们可以看到valueOf()方法返回Integer对象,由于自动装箱,它可以直接用作int值。
NumberFormatException
在示例中,我们可以看到一个try-catch块,该块捕获NumberFormatException,如果传递了无效的数字字符串以将其转换为int则抛出该异常。
public class StringToInt {
public static void main(String[] args) {
String str = "123ab";
try{
Integer num = Integer.valueOf(str);
System.out.println("value - " + num);
// can be used in arithmetic operations now
System.out.println(num+"/3 = " + num/3);
}catch(NumberFormatException exp){
System.out.println("Error in conversion " + exp.getMessage());
throw exp;
}
}
}
输出:
Error in conversion For input string: "123ab" Exception in thread "main" java.lang.NumberFormatException: For input string: "123ab" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.valueOf(Unknown Source) at com.theitroad.programs.StringToInt.main(StringToInt.java:8)

