编写一个程序,读取个数不定的整数,然后查找其中出现频率最高的数字。当输入为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