【发布时间】:2017-05-01 17:08:26
【问题描述】:
我是 Java 初学者,现在,我正在尝试在电脑播放器中创建猜谜游戏。我的 ASL 流利,如果我的英语语法不好,请原谅我。我会尽力说明这一点。
我试图阻止整数中的重复随机数。我使用arraylist从列表中随机生成,似乎随机仍然获取相同的值,我认为随机不会有相同的值。我使用了 Collections.shuffle,但它只适用于数组。我用了arraylist contains,但它要求至少有一个数组才能判断为真或假,开始运行java时数组为空时无法确定真假。 请任何人都可以帮助我阻止这种重复?提前谢谢你。 这个“int a”来自其他类文件(它是一个 Math.random)。
public class GameGuess extends Thread {
int a;
public void Send(int a) {
this.a = a;
ArrayList myArray = new ArrayList();
ArrayList secArray = new ArrayList();
Random rand = new Random();
int p1;
int p2;
do {
p1 = (rand.nextInt(60 - 50) + 50);
p2 = (rand.nextInt(60 - 50) + 50);
myArray.add(p1);
secArray.add(p2);
System.out.println("Player 1: " + p1);
System.out.println("Player 2: " + p2);
if (p1 == a && p2 == a) {
System.out.println("Both Player1 and 2 are tied!");
break;
}
if (p1 == a) {
System.out.println("Player 1 wins!");
}
if (p2 == a) {
System.out.println("Player 2 wins!");
}
if (p1 != a && p2 != a) {
System.out.println("No one win, try again!");
}
} while (p1 != a && p2 != a);
System.out.println("Player 1 picked: " + myArray);
System.out.println("Player 2 picked: " + secArray);
System.out.println("The secret number is " + a);
}
}
【问题讨论】:
-
“我认为随机不会有相同的值” - 随机并不意味着不重复(这已经打破了随机的定义)并且在代码中你总是有 伪-随机数生成器。
-
在向数组添加数字之前,您可以使用 .contains 查看它是否已经是数组列表,如果是则重新滚动。
-
也许您可以使用 TreeSet(因此您只有唯一的编号,按排序顺序),并检查 Set 是否包含您生成的编号。如果是,请再试一次。否则,请使用数字。
-
Collections.shuffle,但它只适用于数组:不。 Collections.shuffle() 将 List 作为参数。 docs.oracle.com/javase/8/docs/api/java/util/…。 shuffle() 有什么问题?为什么在 Java 5 发布 12 年后,您仍然使用原始 ArrayLists 而不是通用 ArrayList
?