1. 程式人生 > >隨機生成 50 個數字,每個數字的範圍在 [10, 50] 之間,統計每個數字出現的次數,最後將每個數字和它出現的次數打印出來

隨機生成 50 個數字,每個數字的範圍在 [10, 50] 之間,統計每個數字出現的次數,最後將每個數字和它出現的次數打印出來

/**
 * 隨機生成 50 個數字,每個數字的範圍在 [10, 50] 之間,統計每個數字出現的次數,最後
 * 將每個數字和它出現的次數打印出來
 */
public class Test4 {
    public static void main(String[] args) {
        Random rand = new Random();

        /*
         * 建立一個二維陣列
         */
        int[][] arr = new int[51][2];
        int k = 50;
        for(int i = 0; i < 51; i++) {
            arr[i][0] = k;
            k++;
        }

        for(int i = 0; i < 50; i++) {
            int r = rand.nextInt(51)+50;
            arr[r-50][1]++;
        }

        for(int i = 0; i < 51; i++) {
            if(arr[i][1] == 0) {
                continue;
            }
            System.out.println(arr[i][0] + "---" + arr[i][1]);
        }
    }
}
public class Test5 {

    public static void main(String[] args) {
        Random rand = new Random();

        HashMap map = new HashMap();
        int k = 50;
        for(int i = 0; i < 51; i++) {
            map.put(k, 0);
            k++;
        }

        for(int i = 0; i < 50; i++) {
            int r = rand.nextInt(51)+50;
            int v = (Integer) map.get(r);
            v++;
            map.put(r, v);
        }

        for(int i = 50; i < 101; i++) {
            if((Integer)map.get(i) == 0) {
                continue;
            }
            System.out.println((Integer)map.get(i));
        }
    }
}