0

Count the occurrence in array

I would like to count the occurrences of each element in the array. Here is my code. But i get error. How to fix it? example output: 5 occurs 2 times 2 occurs 1 times 3 occurs 1 times public class Program { public static void main(String[] args) { int [] num = {5, 2, 5, 3}; int [] count = new int[4]; for (int i = 0; i < num.length; i++) { int temp = num[i]; if (num[i+1] == temp) count[i]++; System.out.println(num[i] + “ occurs “ + count[i] + “ times “); } } }

8th Dec 2018, 5:23 PM
Poo
2 odpowiedzi
+ 2
public class Main { public static void main(String args[]) { int num[]={5,2,5,3}; for(int i=0;i<num.length;i++) { int count = 1; for(int j=i+1;j<num.length;j++) { if(num[i]==num[j]) { ++count; num[j]=-1; } } if(num[i]!=-1) System.out.println(num[i]+" occurs "+count+" times"); } } }
8th Dec 2018, 5:58 PM
Rishi Anand
Rishi Anand - avatar
8th Dec 2018, 8:07 PM
Michal
Michal - avatar