Java中字符串转整数并赋值给整数数组的报错问题解决
问题解决:字符串转整数及最大年龄统计
错误原因分析
你代码里的int[] ages = Integer.valueOf(pieces[1]);报错,核心是类型不匹配:Integer.valueOf(pieces[1])返回的是单个Integer(或int基本类型),但你声明的int[] ages是整数数组,无法直接赋值。
解决方案1:用单个变量跟踪最大年龄(高效)
不需要存储所有年龄,只需在每次输入时更新当前最大年龄即可,代码更简洁高效:
import java.util.Scanner; public class AgeOfTheOldest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int maxAge = Integer.MIN_VALUE; // 初始化为最小整数,兼容所有有效年龄 while (true) { String text = scanner.nextLine(); if (text.isEmpty()) { break; } String[] pieces = text.split(","); // 处理可能的输入格式错误 try { int currentAge = Integer.parseInt(pieces[1].trim()); // 去除年龄字符串前后空格 if (currentAge > maxAge) { maxAge = currentAge; } } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { System.out.println("输入格式错误,请遵循「姓名,年龄」的格式"); } } // 输出结果 if (maxAge != Integer.MIN_VALUE) { System.out.println("年龄最大者的年龄是:" + maxAge); } else { System.out.println("未输入有效数据"); } } }
解决方案2:用动态数组存储所有年龄(需保存数据场景)
如果需要保留所有输入的年龄,推荐用ArrayList(动态数组)来存储,因为无法提前知道输入的行数:
import java.util.ArrayList; import java.util.Scanner; public class AgeOfTheOldest { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ArrayList<Integer> agesList = new ArrayList<>(); while (true) { String text = scanner.nextLine(); if (text.isEmpty()) { break; } String[] pieces = text.split(","); try { int age = Integer.parseInt(pieces[1].trim()); agesList.add(age); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { System.out.println("输入格式错误,请遵循「姓名,年龄」的格式"); } } // 遍历数组找最大年龄 if (!agesList.isEmpty()) { int maxAge = agesList.get(0); for (int age : agesList) { if (age > maxAge) { maxAge = age; } } System.out.println("年龄最大者的年龄是:" + maxAge); } else { System.out.println("未输入有效数据"); } } }
关键注意点
- 用
Integer.parseInt()替代Integer.valueOf():两者都能转字符串为整数,但parseInt()直接返回int基本类型,更适合这里的场景。 - 加上
trim():处理用户输入时可能在逗号后加空格的情况(比如「张三, 25」)。 - 异常处理:避免用户输入格式错误导致程序崩溃。
内容的提问来源于stack exchange,提问作者itsasaddayfs
相关产品推荐
相关产品推荐

