The problem is: Write a program that reads integers between 1-100 and counts the occurrences of each. Assume the input ends with 0. If the number occurs more than once the plural "times" is used in the output. Here is a sample run of the program:
2 occurs 2 times
3 occurs 1 time
4 occurs 1 time
5 occurs 2 times
6 occurs 1 time
23 occurs 1 time
43 occurs 1 time
I have fixed the read integer in my code to no longer be i but a separate variable "index" and understand why I am receiving the out of bounds exception, but I am kind of thick and don't understand how to fix it at the same time as add a sentinel value of 0.
import java.util.Scanner;
public class countNumberOccurrence{
public static void main(String args[]){
int[] numbers = new int[100];
inputArray(numbers);
}
public static void inputArray(int[] myList){
Scanner input = new Scanner(System.in);
System.out.print("Enter integers from 1-100 (input 0 value to end inputs): ");
int index = 0;
for(int i = 1; i < myList.length - 1; i++){
if(i > 0){
index = input.nextInt();
myList[index-1]++;
}
if(myList[index-1] > 1)
System.out.println(index + " occurs " + myList[index-1] + " times ");
else
System.out.println(index + " occurs " + myList[index-1] + " time ");
}
}
}