此代码重复数字,并且使用我编写的 if 语句我认为不应该这样做
class RandomNumber {
public static void main(String[] args) {
int y = 0;
int z = 0;
int[] q = new int[10];
while(y != q.length) {
int x = (int) (Math.random() * 10);
if (x != q[0] || x != q[1] || x != q[2] || x != q[3] || x != q[4] || x != q[5]
|| x != q[6] || x != q[7] || x != q[8] || x != q[9]) {
q[z] = x;
System.out.println(q[z]); // or you could print x it doesn't matter
y++; // I just chose this one to make sure each
z++; // q[] was getting set to a value
}
}
}
}
最佳答案
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Collections.shuffle(list);
问题已解决。而且效率也更高。
关于java - 随机数1-10,不重复。为什么这段代码不起作用。它编译但仍然重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26860462/