温馨提示×

Java中怎么把字符串转换成整数

小亿
83
2024-06-05 15:12:20
栏目: 编程语言

在Java中,可以使用Integer类的parseInt()方法将字符串转换为整数。示例如下:

String str = "123";
int num = Integer.parseInt(str);
System.out.println(num); // 输出:123

如果字符串不是一个有效的整数,将会抛出NumberFormatException异常。因此,在转换之前最好使用try-catch块来捕获异常,例如:

String str = "abc";
try {
    int num = Integer.parseInt(str);
    System.out.println(num);
} catch (NumberFormatException e) {
    System.out.println("字符串不能转换为整数");
}

0