java - 从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] + ",");
}
}
}
解决方案
您没有存储每个随机数的出现次数,此外,您正在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");
});
}
请注意,这些示例不会在相同范围内创建相同的数字。
推荐阅读
- java - 您将如何测试静态方法 URLEncoder.encode?
- sql - 抑制/消除嵌套选择的 datagrip sql 重新格式化
- amazon-web-services - YAML 中 AWS Cloudformation 模板中的 `Ref:logicalName` 和 `!Ref logicalName` 有什么区别?
- c# - 如何用 C# 重新构造嵌套的 json 数据?或团结
- wordpress - 在 woocommerce 网站登录并注册
- vmware-clarity - 如何在页面上居中内嵌单选按钮?
- python - QTextEdit 的 QTextDocument 在 SetText 后无法调整页面大小
- php - 如何使用 php 激活 python 脚本并且在 time.sleep 进行时不加载页面
- android - Realm 数据库是否可移植
- r - 当 R 中已知矩阵的列数时,如何将多列添加到矩阵中?