Java命令行参数统计程序报ArrayIndexOutOfBoundsException异常求助
问题修复方案
报错根因
你代码触发ArrayIndexOutOfBoundsException的核心问题是访问命令行参数数组的下标逻辑错误:
- 命令行传入的第一个参数
args[0]是剩余参数的个数,需要统计的剩余参数是从args[1]才开始的 - 你的循环里直接用
args[i]取值,既把不需要统计的count值也纳入了统计逻辑,当count值大于你实际传入的参数总数时,就会触发数组越界。
另外代码还缺少必要的参数合法性校验,没有提前判断用户传入的参数总数是否匹配第一个参数声明的数量。
修改后的完整代码
public class Distribution100 { public static void main(String[] args) { // 先校验有没有传第一个参数 if (args.length < 1) { System.out.println("用法错误:请输入至少1个参数,第一个参数为后续数字的个数"); return; } int count = Integer.parseInt(args[0]); // 校验实际传入的剩余参数数量是否和声明的一致 if (args.length != count + 1) { System.out.printf("用法错误:声明后续有%d个数字,实际只传入了%d个%n", count, args.length - 1); return; } int[] array = new int[count]; int low = 0; int high = 0; for (int i = 0; i < count; i++) { // 剩余参数从args[1]开始,所以取i+1位置的参数 array[i] = Integer.parseInt(args[i+1]); if (array[i] >= 1 && array[i] <= 50) { low++; } else if (array[i] > 50 && array[i] <= 100) { high++; } else { // 可选:提示不符合范围的参数 System.out.printf("警告:参数%d超出1~100的范围,将被忽略%n", array[i]); } } System.out.println(low + " numbers are less than or equal to 50."); System.out.println(high + " numbers are higher than 50."); } }
验证示例
比如你在命令行执行:java Distribution100 3 20 60 90
输出结果为:
1 numbers are less than or equal to 50. 2 numbers are higher than 50.
内容的提问来源于stack exchange,提问作者gizmo.java
相关产品推荐
相关产品推荐

