I couldn't create a method to count the number of occurrences

by isikonur   Last Updated June 13, 2019 08:26 AM

I've created a method to count the number of occurrences in an array, but I can't compile and run it.

Compiler gives the error:

The method occurence(int[]) in the type countOfOccurence is not applicable for the arguments (int)

public class countOfOccurence {

    public static void main(String[] args) {
        int[] number = {15,16,14};

        System.out.print(occurence(number[15]));
    }

    public static int occurence(int[] number) {

        int count = 0;
        for(int i = 0 ; i < number.length; i++) {

            for(int k = 0 ; i < number.length; i++) {
                if(number[k] == number[i]) {
                    count++;
                }
            }
        }
        return count;
    }
}
Tags : java arrays


Answers 1


Your occurrence method is expecting an array, but you are just passing an int to it (the 15th element from your array, which will also cause a runtime error as there are only 3 elements in your array).

But I also think your logic is off here, your current method (given that it would compile) will count all occurrences of all duplicate numbers in your array, not just the number you would want.

First off all, your occurrence method would need 2 arguments, the actual array and the number you want to count the occurrences of. You don't need an inner loop, just keep your outer loop and check inside whether the array element equals your desired number.

public static void main(String[] args) {
  int[] number = {15,16,14};
  System.out.print(occurence(number, 15));
}

public static int occurence(int[] numberArray, int number) {
  int count = 0;
  for(int i = 0 ; i < numberArray.length; i++) {
    if(numberArray[i] == number) {
      count++;
    }
  }
  return count;
}

Of course there are better / cleaner ways to count occurrences of elements in an array, for example using the Streams api, if you would want to optimize.

TheWhiteRabbit
TheWhiteRabbit
June 13, 2019 08:20 AM

Related Questions


Updated June 03, 2016 09:11 AM

Updated September 25, 2017 03:26 AM

Updated October 25, 2017 07:26 AM

Updated November 04, 2018 20:26 PM