編寫一個程序,讀取個數不定的整數,然后查找其中出現頻率最高的數字。當輸入為0時,表示結束輸入。


編寫一個程序,讀取個數不定的整數,然后查找其中出現頻率最高的數字。當輸入為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);
        }
        
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM