首页 > 解决方案 > 从0到10的20个随机数数组。如何计算其中的特定数字?

问题描述

我做了这个数组,但我在努力计算数字。我可以通过使用“IF”10 次来做到这一点,但这对我来说似乎是错误的。也许循环“for”在这里最好使用,但我不知道如何解决这个问题。

import java.util.Random;


public class zadanie2 {
    public static void main(String[] args) {
        int array[];
        array = new int[20];


        for (int i = 0; i < array.length; i++) {
            Random rd = new Random();
            array[i] = rd.nextInt(10);
            System.out.print(array[i] + ",");
        }
    }
}

标签: javaarraysrandomnumberscounting

解决方案


您没有存储每个随机数的出现次数,此外,您正在Random每次迭代中创建一个新的,不应该这样做。

如果您想存储这些事件,请为此定义一个适当的数据结构,否则您将无法存储它们。我用过一个Map<Integer, Integer>,看这个例子:

public static void main(String[] args) {
    // define a data structure that holds the random numbers and their count
    Map<Integer, Integer> valueOccurrences = new TreeMap<>();
    // define a range for the random numbers (here: between 1 and 10 inclusively)
    int minRan = 1;
    int maxRan = 10;

    for (int i = 0; i < 20; i++) {
        // create a new random number
        int ranNum = ThreadLocalRandom.current().nextInt(minRan, maxRan + 1);
        // check if your data structure already contains that number as a key
        if (valueOccurrences.keySet().contains(ranNum)) {
            // if yes, then increment the currently stored count
            valueOccurrences.put(ranNum, valueOccurrences.get(ranNum) + 1);
        } else {
            // otherwise create a new entry with that number and an occurrence of 1 time
            valueOccurrences.put(ranNum, 1);
        }
    }

    // print the results
    valueOccurrences.forEach((key, value) -> {
        System.out.println(key + " occurred " + value + " times");
    });
}

作为替代方案,您可以使用 a Random,但对所有迭代使用一个实例:

public static void main(String[] args) {
    // define a data structure that holds the random numbers and their count
    Map<Integer, Integer> valueOccurrences = new TreeMap<>();
    // create a Random once to be used in all iteration steps
    Random random = new Random(10);

    for (int i = 0; i < 20; i++) {
        // create a new random number
        int ranNum = random.nextInt();
        // check if your data structure already contains that number as a key
        if (valueOccurrences.keySet().contains(ranNum)) {
            // if yes, then increment the currently stored count
            valueOccurrences.put(ranNum, valueOccurrences.get(ranNum) + 1);
        } else {
            // otherwise create a new entry with that number and an occurrence of 1 time
            valueOccurrences.put(ranNum, 1);
        }
    }

    // print the results
    valueOccurrences.forEach((key, value) -> {
        System.out.println(key + " occurred " + value + " times");
    });
}

请注意,这些示例不会在相同范围内创建相同的数字。


推荐阅读