I am trying to get an array called frequencyCounters count the amount of times a number repeats in an array called array. The index is supposed to refer to the number i.e index 0 counts how many times 0 occurs and index 1 counts how many times 1 occurs. It sort of works but not perfectly.
import java.util.*;
class ArrayTest {
public static void main(String[] args) {
int[] array = new int[]{1, 1, 4, 4, 4, 5, 5, 5, 5, 7, 8, 8, 8, 8, 9};
Arrays.sort(array);
int max = array[array.length - 1];
int[] frequencyCounter = new int[max];
System.out.println("max is " + max);
int checkNumber = 1;
int index = 0;
int length = array.length - 1;
for (int i = 0; i <= 8; i++) {
System.out.println("i is " + i);
if (index == 0) {
System.out.println("running index=0 statement");
while (checkNumber == array[index]) {
if (i == 0) {
System.out.println("Running i==0 statement");
frequencyCounter[i] = frequencyCounter[i] + 1;
} else if (i != 0) {
System.out.println("Running i!=0 statement");
frequencyCounter[i - 1] = frequencyCounter[i - 1] + 1;
}
index = index + 1;
}
checkNumber = checkNumber + 1;
} else {
System.out.println("index is " + index);
System.out.println("running i=0 else statement");
while (checkNumber == array[index]) {
if (i == 0) {
System.out.println("Running i==0 statement");
frequencyCounter[i] = frequencyCounter[i] + 1;
} else {
System.out.println("Running i!=0 statement");
frequencyCounter[i - 1] = frequencyCounter[i - 1] + 1;
}
index = index + 1;
}
checkNumber = checkNumber + 1;
}
System.out.println("index is " + index + " at end of loop for");
}
int output = 1;
for (int Z = 0; Z <= 8; Z++) {
System.out.printf("The number %d repeats %d
times",output,frequencyCounter[Z]
output++;
}
}
}
For some reason index suddenly jumps from 5 to 9 and then to 14 in my output statements. I am a highschool student and would love some help on this question :) I need to find the mode(s) of the array. I am not allowed to use fancy stuff like hashmaps. I can only use the array class and loops with simple operations.