java - 如何用限制为 0-20 的随机数填充数组
问题描述
我在将随机生成器放入数组时遇到问题,如何从数组中的 0-9 中获取 #20 随机数?然后你计算这些数字的出现次数。
导入 java.util.Random;
公共类 CountDigits {
public static void main(String[] args) {
Random digit = new Random();
int Random[] = new int [20];
int Digits[] = {0,1,2,3,4,5,6,7,8,9};
int Count [] = new int [10];
for ( int i = 0; i < Digits.length; i++) {
for( int j = 0; j < Random.length; j++) {
if ( Digits [i] == Random [j] )
Count[i]++;
}
}
for ( int i = 0; i < Count.length; i++) {
if ( Count[i] == 1)
System.out.printf(" %d occurs 1 time " , Digits[i] );
else
System.out.printf("%d occurs %d times" , Digits[i], Count[i]);
}
结果到目前为止:: 0 发生 20 次 1 发生 0 次 2 发生 0 次 3 发生 0 次 4 发生 0 次 5 发生 0 次 6 发生 0 次 7 发生 0 次 8 发生 0 次 9 发生 0 次
解决方案
您忘记为数组元素分配随机数。这个答案可以查看随机数是如何生成的。
您需要调用 Random 对象的 nextInt(an integer) 方法。如果你给它 25,它将返回一个介于 0-24 之间的随机整数。
示例用法:
Random rand = new Random();
int random_int = rand.nextInt(50); // --------> Random integer 0-49
和完整的代码:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random digit = new Random();
int Random[] = new int[20];
for (int x=0;x<20;x++) {
Random[x] = digit.nextInt(10);
}
int Digits[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int Count[] = new int[10];
for (int i = 0; i < Digits.length; i++) {
for (int j = 0; j < Random.length; j++) {
if (Digits[i] == Random[j])
Count[i]++;
}
}
for (int i = 0; i < Count.length; i++) {
if (Count[i] == 1)
System.out.printf(" %d occurs 1 time ", Digits[i]);
else
System.out.printf("%d occurs %d times", Digits[i], Count[i]);
}
}
}
输出:
0 occurs 2 times1 occurs 2 times 2 occurs 1 time 3 occurs 3 times4 occurs 6 times 5 occurs 1 time 6 occurs 2 times7 occurs 0 times 8 occurs 1 time 9 occurs 2 times
您可以像这样打印随机数
for (int x=0;x<20;x++) {
System.out.println(Random[x]);
}
推荐阅读
- c# - 有两个非常大的列表/集合 - 如何有效地检测和/或删除重复项
- android - React js 应用程序具有相同的文件夹图像,但在 ios png 图像中显示 alpha 透明度问题
- sql - 如果当前行中不可用,则从前一行获取日期值
- ios - 将值从 Objective-C 类传递给 Swift TableViewCell
- php - 找出数组中有多少个数大于 N
- ionic3 - 卡在复制完成,无法进行生产构建
- layout - 图表的自动布局
- python - 如何在 Django REST 框架中序列化继承的模型
- go - 由于某种原因,将值传递给通道正在阻塞线程
- mysql - 通过查询自动分配列