1、随机生成50个数字(整数),每个数字的范围是[10,50],统计每个数字出现的次数以及出现次数最多的数字与他的个数,最后将每个数字及其出现的次数打印出来,如果某个数字出现次数为0,则不要打印它,打印时按照数字的升序排列。(用map实现)
package com.xuyilong;
import java.util.Map; import java.util.TreeMap;
public class CountNum { public static void main(String[] args) { int a; Map<Integer, Integer> m = new TreeMap<>(); for (int i = 0; i < 50; i++) { a = (int) (Math.round((Math.random() * 40)) + 10); System.out.print(a+(((i+1)%10==0)?"\n":" ")); if (!m.containsKey(a)) { m.put(a, 1); } else { m.put(a, m.get(a) + 1); } } int maxK = 0; String str = ""; int i=1; for (Map.Entry<Integer, Integer> e : m.entrySet()) { System.out.print("数字" + e.getKey() + "出现了" + e.getValue() + "次"+(((i++)%5==0)?"\n":" ")); if (e.getValue() == maxK) { str = str + e.getKey() + ", "; } else if (e.getValue() > maxK) { maxK = e.getValue(); str = e.getKey().toString() + ", "; } } System.out.println("\n出现最多次数的数字是:" + str + "次数为" + maxK + "次"); } }
|