在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写数组并循环输入数据