gpt4 book ai didi

java - 20个从0到10的随机数字数组。如何统计其中的具体数字?

转载 作者:行者123 更新时间:2023-12-02 09:23:48 24 4
gpt4 key购买 nike

我制作了这个数组,但我很难计算数字。我可以通过使用“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] + ",");
}
}
}

最佳答案

您没有存储每个随机数的出现次数,此外,您正在创建一个新的 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");
});
}

作为替代方案,您可以使用 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");
});
}

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

关于java - 20个从0到10的随机数字数组。如何统计其中的具体数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58483698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com