我堆了一会儿。我尝试调试,但找不到解决方案。我正在尝试计算数字的出现。所以我的问题是当我打印输出时
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
代替
1 occurs 2 times
0 occurs 2 times
2 occurs 2 times
3 occurs 2 time
10 occurs 1 times
4 occurs 1 times
因此,如果数字出现的次数超过1,则应该只说一次,而不是出现的次数。欢呼这是代码
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");
}
}
}
最佳答案
另一个选项是番石榴的Multiset类,它将为您跟踪计数:
int values[] = ...;
Multiset<Integer> ms = HashMultiset.create();
ms.addAll(Ints.asList(list));
int count0 = ms.count(Integer.valueOf(0));
int count1 = ms.count(Integer.valueOf(1));
在这里,Multiset,HashMultiset和Ints都是番石榴类。
请注意,Multiset通过使用Map和counter来跟踪计数器,几乎可以完成上面提到的某些事情。它只是从您身上抽象出来,以使您的代码更简单。