I'm trying to solve following simple programming exercise: "Write a program that reads the integers between 1 and 10 and counts the occurrences of each. Assume the input ends with 0". I've come up with following solution. I'm not familiar with debugger and trying trace ArrayIndexOutOfBoundsException
last 3 hours. Maybe someone is able to see the where ArrayIndexOutOfBoundsException
occurs?
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。
The problem is here:
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;
}
The solution is in:
counts[(number - 1 > 0) ? number - 1 : 0]++;
This checks if (number-1) is greater than zero. If not it uses 0. If true it uses number -1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.