我试图解决以下简单的编程练习:"编写一个程序,读取1到10之间的整数,并计算每个的出现次数。假设输入以0"结束。我提出了以下解决方案。我不熟悉调试器并且在过去3个小时内尝试跟踪ArrayIndexOutOfBoundsException
。也许有人能够看到ArrayIndexOutOfBoundsException
发生的地方?
import java.util.Scanner;
public class Exercise07_03 {
/** Main method */
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
System.out.print("Enter up to 10 integers between 1 and 10" +
"inclusive (input ends with zero): ");
int i = 0;
do {
numbers[i] = input.nextInt();
i++;
} while (numbers[i] != 0 && i != 9);
displayCounts(countNumbers(numbers));
}
/** Count the occurrences of each number */
public static int[] countNumbers(int[] numbers) {
int[] counts = new int[10];
for (int i = 0; i < counts.length; i++)
counts[numbers[i] - 1]++;
return counts;
}
/** Display counts */
public static void displayCounts(int[] counts) {
for (int i = 1; i < counts.length + 1; i++)
if (counts[i - 1] != 0)
System.out.println(i + " occurs " + counts[i - 1] + " time");
}
}
答案 0 :(得分:1)
counts[numbers[i] - 1]++;
如果输入包含0,结果为-1。
答案 1 :(得分:1)
问题在于:
public static int[] countNumbers(int[] numbers) {
int[] counts = new int[10];
for (int i = 0; i < counts.length; i++)
counts[numbers[i] - 1]++;
return counts;
}
解决方案是:
counts[(number - 1 > 0) ? number - 1 : 0]++;
检查(number-1)是否大于零。如果不是,则使用0.如果为true,则使用数字-1。