计算数组中数字的出现次数

我堆了一会儿。 我试过调试,但我无法弄清楚解决方案。 我试图计算数字的出现次数。 所以我的问题是,当我打印输出时,它是

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"); } } } 

另一种选择是guava的Multiset类,它将为您跟踪计数:

 int values[] = ...; Multiset 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都是番石榴类。

请注意,通过使用Map和计数器来跟踪计数器,Multiset几乎完成了上面提到的人。 它只是从你身上抽象出来,使你的代码变得更简单。

使用HashMap, ht来管理您的计数

 if (ht.get(newNumber) == null) { ht.put(newNumber, 1); } else { ht.put(newNumber, ++ht.get(newNumber)); } 

get(..)之前修正了HashMap++ HashTable

你有一个循环来计算事件,这也给出一个运行总计。 看起来你想要的只是在计数完成时打印总数。 即它应该在另一个循环中。

好的,我会试着给你一两个提示。

  1. 由于您为每个不止一次出现的数字打印了几行,因此在完成计数之前,您可能不应该打印任何内容。
  2. 看起来您的输出应该在出现次数后进行排序。 如果是这种情况,保存数组中的计数可能不是最好的主意。 请考虑使用Map ,其中键是数字,值是出现次数。
  import java.io.BufferedReader; import java.io.InputStreamReader; public class NumberRepetition { public static void main(String[] args) throws Exception { int size; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter size of array"); size=Integer.parseInt(br.readLine()); int el; int[] a=new int[size]; for(int i=0;ia[j+1]) { int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } int count=0; for(int i=0;i 

创建一个HashMap并将新条目放在地图中,其中键值为值,其中值为Integer。

如果遇到相同的char,则递增与该键关联的整数值。 它是一个新密钥并将值设置为1。

 Integer entryValue; Map map = new HashMap(); for ( int i =0; i < s1.length(); i++) { entryValue = (Integer)map.get(s1.charAt(i)); if (entryValue == null) { map.put(s1.charAt(i), new Integer(1)); } else { map.put(s1.charAt(i), new Integer(entryValue.intValue()+1)); } }