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

示例代码如下:

String str = "12345";
int num = Integer.parseInt(str);
System.out.println(num);

输出结果为:

12345

请注意,如果字符串无法解析为整数,将抛出NumberFormatException异常。因此,在转换之前最好进行异常处理。

String str = "abc";
try {
    int num = Integer.parseInt(str);
    System.out.println(num);
} catch (NumberFormatException e) {
    System.out.println("字符串无法解析为整数");
}

输出结果为:

字符串无法解析为整数
java string转int的方法

原文地址: https://www.cveoy.top/t/topic/iKM8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录