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 “); } } }
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");
}
}
}
+ 2
My proposition
https://code.sololearn.com/cJhl45XIduCF/#java