温馨提示×

java无法将string转换为int怎么解决

小亿
173
2023-12-22 16:49:54
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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怎么解决

0