編寫一個程序,讀取個數不定的整數,然后查找其中出現頻率最高的數字。當輸入為0時,表示結束輸入。
例如,如果輸入的數據是2 3 40 3 5 4 -3 3 3 2 0,那么數字3的出現頻率是最高的。如果出現頻率最高的數字不是一個而是多個,則將它們全部輸出。
import java.util.*; public class Exercise2 { public static void main(String[] args) { Scanner reader=new Scanner(System.in); HashMap<Integer,Integer> tm=new HashMap<Integer,Integer>(); while (true) { int a=reader.nextInt(); if (a==0) { break; } if (tm.containsKey(a)) { int value1=tm.get(a); value1++; tm.put(a,value1); } else { tm.put(a,1); } } Collection<Integer> c = tm.values(); Object[] obj = c.toArray(); Arrays.sort(obj); Set keySet=tm.keySet(); Iterator it2=keySet.iterator(); while (it2.hasNext()) { Object key=it2.next(); Object value=tm.get(key); if (obj[tm.size()-1]==value) { System.out.println(key); } //System.out.println(key+":"+value); } } }