當前位置:編程學習大全網 - 腳本源碼 - 求編程代碼,要求如下。代碼的編程軟件名稱說下。

求編程代碼,要求如下。代碼的編程軟件名稱說下。

/*

java實現,統計各數字出現次數,按出現姿數從大到小排序輸出:

測試如下:

數字: 3 次數: 10

數字: 5 次數: 6

數字: 2 次數: 5

數字: 6 次數: 5

數字: 1 次數: 4

數字: 4 次數: 4

數字: 7 次數: 4

數字: 8 次數: 4

數字: 10 次數: 4

數字: 9 次數: 3

數字: 11 次數: 1

*/

import java.util.*;

import java.util.Map.Entry;

public class MapSort {?

public static void main(String[] args) {

Map<Integer,Integer> map = new HashMap<Integer,Integer>();

for(int i = 1;i<12;i++){

map.put(i, 0);

}

for(int i = 0;i<10;i++){

Scanner input = new Scanner(System.in);

System.out.print("輸入5個1~11之間的數字,以,隔開: ");

String str = input.nextLine();

String []num_str =str.split(",");

for (int j = 0;j<num_str.length;j++){

int num = Integer.parseInt(num_str[j]);

if (num > 11 || num < 1)

{

System.out.println("請輸入1到11之間的整數");

return;

}else

{

int count = map.get(num);

map.put(num, count==0?1:count+1);

}

}

}

map = sortMap(map);

for (Integer key : map.keySet()) {

? System.out.println("數字: "+ key + " 次數: " + map.get(key));

}

}

//實現map按value從大到小排序

public static Map sortMap(Map oldMap) { ?

? ArrayList<Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(oldMap.entrySet()); ?

? Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() { ?

? @Override ?

? public int compare(Entry<Integer, Integer> arg0, Entry<Integer, Integer> arg1) { ?

? return ? arg1.getValue() - arg0.getValue(); ?

? } ?

? }); ?

? Map newMap = new LinkedHashMap(); ?

? for (int i = 0; i < list.size(); i++) { ?

? newMap.put(list.get(i).getKey(), list.get(i).getValue()); ?

? } ?

? return newMap; ?

} ?

}

  • 上一篇:易遊加速器的什麽是易遊加速器
  • 下一篇:龍葵菜圖片及功效
  • copyright 2024編程學習大全網