无法追踪 java.lang.ArrayIndexOutOfBoundsException:
Can't trace an java.lang.ArrayIndexOutOfBoundsException:
我正在尝试解决以下简单的编程练习:"Write a program that reads the integers between 1 and 10 and counts the occurrences of each. Assume the input ends with 0"。我想出了以下解决方案。我不熟悉调试器并尝试跟踪 ArrayIndexOutOfBoundsException
最后 3 个小时。也许有人能够看到 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");
}
}
counts[numbers[i] - 1]++;
如果输入包含 0,则结果为 -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。如果为真,则使用数字 -1。
我正在尝试解决以下简单的编程练习:"Write a program that reads the integers between 1 and 10 and counts the occurrences of each. Assume the input ends with 0"。我想出了以下解决方案。我不熟悉调试器并尝试跟踪 ArrayIndexOutOfBoundsException
最后 3 个小时。也许有人能够看到 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");
}
}
counts[numbers[i] - 1]++;
如果输入包含 0,则结果为 -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。如果为真,则使用数字 -1。