在Java中,可以使用`Integer.parseInt()`方法将字符串转换为整数。以下是一个示例代码:
public class Main {
public static void main(String[] args) {
String str = “123”;
int num = Integer.parseInt(str);
System.out.println(num);
}
}
输出结果为:
123
请确保字符串中的内容可以被解析为整数,如果字符串中包含非数字字符,则会抛出NumberFormatException
异常。因此,在使用Integer.parseInt()
方法时,应该使用try-catch
块来捕获异常并进行处理。以下是一个例子:
public class Main {
public static void main(String[] args) {
String str = “abc”;
try {
int num = Integer.parseInt(str);
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println(“无法将字符串转换为整数”);
}
}
}
输出结果为:
无法将字符串转换为整数
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:JAVA中string无法转换为bigdecimal怎么解决