// 将 Java 中的 String 转换为 int 的示例代码
public class StringToIntExample {
public static void main(String[] args) {
// 定义一个字符串
String str = "12345";
// 方法 1: 使用 Integer.parseInt() 方法
try {
int num1 = Integer.parseInt(str);
System.out.println("使用 Integer.parseInt() 转换的结果: " + num1);
} catch (NumberFormatException e) {
System.out.println("转换失败,输入的字符串不是有效的整数格式");
}
// 方法 2: 使用 Integer.valueOf() 方法
try {
Integer num2 = Integer.valueOf(str);
System.out.println("使用 Integer.valueOf() 转换的结果: " + num2);
} catch (NumberFormatException e) {
System.out.println("转换失败,输入的字符串不是有效的整数格式");
}
}
}
Integer.parseInt():这是最常用的方法,它将字符串直接转换为基本类型 int。如果字符串不能被解析为整数,则会抛出 NumberFormatException 异常。
Integer.valueOf():这个方法返回的是 Integer 对象而不是基本类型 int。虽然它可以用于获取 int 值(通过自动拆箱),但它通常用于需要 Integer 对象的场景。同样,如果字符串不能被解析为整数,也会抛出 NumberFormatException。
这两种方法都可以用来将字符串转换为整数,选择哪种方法取决于具体的需求。
下一篇:java获取文件大小
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站