What should I say, it took me a while to figure out what the two variables count and countNum , maybe some comments are needed. But finally, I found an error.
Suppose the ten numbers entered are: 5, 6, 7, 8, 5, 6, 7, 8, 5, 6
After sorting numList : 5, 5, 5, 6, 6, 6, 7, 7, 8, 8
The count array returned by occurrences() should be: [1, 2, 3, 1, 2, 3, 1, 2, 1, 2]
In fact, the only useful numbers in this array of results are:
count[2]: 3 count number for numList[2]: 5 count[5]: 3 count number for numList[5]: 6 count[7]: 2 count number for numList[7]: 7 count[9]: 2 count number for numList[9]: 8
Other numbers, such as the first two numbers 1, 2 to 3 , are only used to calculate the sums of occurrences step by step, right? So, your loop logic should be changed as follows:
remove the first if block:
if (num == 0) { if (count[num] <= 1) System.out.println (numList[num] + " occurs " + count[num] + " time"); if (count[num] > 1) System.out.println (numList[num] + " occurs " + count[num] + " times"); }
Change the second if condition to:
if ((num + 1) == MAX_NUM || numList[num] != numList[num + 1]) { ...... }
After that, your code should work fine as expected.
By the way, you really don't need to do this so confusing. Just try the HashMap :)