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

453
2024/5/8 15:12:20
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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("字符串不能转换为整数");
}

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java hook框架的用法是什么