// 将字符串转换为整数的几种常见方法
// 方法1: 使用 Integer.parseInt()
String str = "123";
try {
int num = Integer.parseInt(str);
System.out.println("转换结果: " + num); // 输出: 转换结果: 123
} catch (NumberFormatException e) {
System.out.println("输入的字符串不是有效的整数格式");
}
// 方法2: 使用 Integer.valueOf()
String str2 = "456";
try {
Integer num2 = Integer.valueOf(str2);
System.out.println("转换结果: " + num2); // 输出: 转换结果: 456
} catch (NumberFormatException e) {
System.out.println("输入的字符串不是有效的整数格式");
}
// 方法3: 使用自定义逻辑逐位计算(适用于特殊情况)
String str3 = "789";
int result = 0;
for (int i = 0; i < str3.length(); i++) {
result = result * 10 + (str3.charAt(i) - '0');
}
System.out.println("转换结果: " + result); // 输出: 转换结果: 789
int 类型的值。如果字符串包含非数字字符,会抛出 NumberFormatException 异常。parseInt() 类似,但它返回的是 Integer 对象而不是基本数据类型 int。同样会在无效输入时抛出异常。以上三种方法都可以实现从字符串到整数的转换,具体选择哪种方法取决于实际需求和使用场景。
上一篇:java callable
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站