Java 从1到25生成3个随机数?(爪哇)
所以,我试图生成一个长度为3的数组,其中包含从1到25的随机唯一数。我不明白为什么我的代码不起作用,我非常感谢您的帮助Java 从1到25生成3个随机数?(爪哇),java,arrays,random,unique,Java,Arrays,Random,Unique,所以,我试图生成一个长度为3的数组,其中包含从1到25的随机唯一数。我不明白为什么我的代码不起作用,我非常感谢您的帮助 public void generateRandom() { for(int j=0; j<3; j++) { dots[j] = (int) (Math.random()*(col*row)+1); System.out.println(dots[j]); for(int i=j; i>0; i--) {
public void generateRandom() {
for(int j=0; j<3; j++) {
dots[j] = (int) (Math.random()*(col*row)+1);
System.out.println(dots[j]);
for(int i=j; i>0; i--) {
if(dots[j]==dots[j-1]) {
generateRandom();
}
}
}
}
dots[]是我试图存储3个唯一随机数的数组。顺便说一句,col*row==25。每次GeneratorDOM调用自身时,它都会从头开始使用第一个随机数,而不是为当前位置选择一个新的随机数。这里有一点不同的方法。它依赖于使用指定的一组值创建ArrayList,然后对该列表进行洗牌。列表被洗牌后,您可以根据洗牌列表中的前三个元素创建一个数组
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 26; i++){
list.add(i);
}
Collections.shuffle(list);
Integer[] randomArray = list.subList(0, 3).toArray(new Integer[3]);
for(Integer num:randomArray){
System.out.println(num);
}
}
这是一种方法
public void generateRandom() {
for(int j=0; j<3; j++) {
boolean f;
do {
dots[j] = (int) (Math.random()*(col*row)+1);
f = false;
for(int i=j-1; i>=0; i--) {
if(dots[i]==dots[j]) {
f = true;
break;
}
}
if (!f)
System.out.println(dots[j]);
} while (f);
}
}
它将重复生成数字,直到没有找到重复的数字
for(int j=0;j<3;j++)
dots[j]=(int)(Math.random()*Integer.MAX_VALUE)%25+1;
由于Math.random无论如何都是一个随机数,因此乘以Integer.MAX_值不会影响随机性。另外,如果你想解释为什么你的代码不起作用,那是因为如果这个数字相对较小,比如说在0.001以下,当你乘法时,你会得到整数,得到0。这应该没关系吧?因为不管怎样,最终数组将填充3个随机数。如果是这样的话,你一开始就不会有问题。先告诉我这个方法。如果范围相当小,这是实现这一点的简单方法。等等。。。为什么先使用for,然后使用递归性?