I am stack for a while . I tried debugging but I couldn’t figure out the solution. I am trying to count the occurrence of numbers. So my problem is that when I print the output it is
3 occurs 1 times
1 occurs 1 times
0 occurs 1 times
2 occurs 1 times
1 occurs 2 times
3 occurs 2 times
2 occurs 2 times
0 occurs 2 times
10 occurs 1 times
4 occurs 1 times
instead of
1 occurs 2 times
0 occurs 2 times
2 occurs 2 times
3 occurs 2 time
10 occurs 1 times
4 occurs 1 times
so if the number has more than 1 occurrence it should say it only once not as many times as there is occurrences. Cheers Here is the code
import java.util.*;
public class CountingOccuranceOfNumbers
{
public static void main(String[] args)
{
countNumbers();
}
public static void countNumbers()
{
Scanner input = new Scanner(System.in);
Random generator = new Random();
int[] list = new int[11];
int[] counts = new int[150];
int counter = 0;
int number = 1;
while(counter <= 10)
{
number = generator.nextInt(11);
list[counter] = number;
counter++;
}
for(int i=0; i<list.length - 1; i++)
{
counts[list[i]]++;
// System.out.print(list[i] + " ");
System.out.println(list[i] +" occurs " + counts[list[i]] + " times");
}
}
}
Another option is guava’s Multiset classes, which will track the count for you:
Here, Multiset, HashMultiset and Ints are all guava classes.
Note that Multiset does pretty much what someone mentioned above by using a Map and counter to track the counters. It’s just abstracted away from you to make your code simpler.