Java 字符串转整数:parseInt() 方法详解及异常处理
在 Java 中,可以使用 Integer.parseInt()
方法将字符串转换为整数类型。
示例代码如下:
String str = '12345';
int num = Integer.parseInt(str);
System.out.println(num); // 输出:12345
需要注意的是,如果字符串无法转换为整数类型,会抛出 NumberFormatException
异常。因此,在进行转换之前,最好使用 try-catch
语句来捕获异常。
String str = 'abc';
try {
int num = Integer.parseInt(str);
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println('字符串无法转换为整数类型');
}
原文地址: http://www.cveoy.top/t/topic/pdm4 著作权归作者所有。请勿转载和采集!