Counting an Occurrence in an Array (Java)

I am completely stumped. I took a break for a few hours and I can’t seem to figure this one out. It’s upsetting!

I know that I need to check the current element in the array and see if it appears elsewhere in the array. The idea is to output the following:

The user is asked to enter 10 integers and those integers are assigned to an array (hence the “numbers” as a paremeter for the method). Let’s say I enter “1, 1, 2, 3, 3, 4, 5, 6, 7, 8.” The printed results should be “1 occurs 2 times. 2 occurs 1 time. 3 occurs 2 times. 4 occurs 1 time. 5 occurs 1 time. 6 occurs 1 time. 7 occurs 1 time. 8 occurs 1 time.” This printing will be done in a separate method.

Everything in my code works except for this method that I created to count the occurrences.

public static int getOccurrences(int[] numbers)
    int count = 0;

    for (int i = 0; i < numbers.length; i++)
        int currentInt = numbers[i];;

        if (currentInt == numbers[i])

    return count;

I know what the issue is here. I set the current integer element in the array to the variable currentInt. The if statement counts every integer element in the array, hence the output being “[[email protected] occurs 10 times.”

How do I keep track of the occurrences of each element in the array?

Leave a Comment