Java String

Java中String转int型的方法以及错误处理

小云
106
2024-02-04 11:22:34
栏目: 编程语言

在Java中,可以使用Integer.parseInt()方法将字符串转换为int型。该方法将字符串作为参数,并返回对应的int值。

以下是一个示例:

String str = "12345";
try {
    int num = Integer.parseInt(str);
    System.out.println(num);
} catch (NumberFormatException e) {
    System.out.println("字符串无法转换为int型");
}

在上面的示例中,我们使用Integer.parseInt()方法将字符串"12345"转换为int值,并将其存储在num变量中。如果字符串无法转换为int型,则会抛出NumberFormatException异常。可以使用try-catch语句来捕获这个异常并进行相应的错误处理。

注意:使用Integer.parseInt()方法时,字符串必须表示整数。如果字符串中包含非数字字符,则会抛出NumberFormatException异常。

0
看了该问题的人还看了