我是Java初学者,现在,我正在尝试在计算机化播放器中创建猜猜游戏。我是ASL流利的,如果我用英语写一个糟糕的语法,请原谅我。我会尽力说清楚。
我试图阻止整数中的重复随机数。我使用arraylist从列表中随机制作,似乎随机仍然拿起相同的值,我认为随机赢得了相同的值。我使用了Collections.shuffle,但它只适用于数组。我使用了arraylist contains,但它需要至少有一个数组才能生成true或false,当java在开始运行时,当数组为空时,它无法确定true和false。 请有人帮我阻止这种重复吗?提前谢谢你。 这个" 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);
}
}
答案 0 :(得分:1)
使用Set
拒绝已经尝试过的随机猜测。 Set
比List
更有效,但更重要的是,它会让读取代码的任何人清楚地知道集合中的每个元素只能出现一次。这使您的代码更加清晰。
Set<Integer> p1Guesses = new LinkedHashSet();
Set<Integer> p2Guesses = new LinkedHashSet();
int p1, p2;
do {
p1 = rand.nextInt(10) + 50;
while (!p1Guesses.add(p1))
p1 = rand.nextInt(10) + 50;
p2 = rand.nextInt(10) + 50;
while (!p2Guesses.add(p2))
p2 = rand.nextInt(10) + 50;
...
通过使用LinkedHashSet
,将记录猜测的顺序。如果添加的元素已经存在于集合中,add()
的{{1}}方法将返回Set
,因此该条件可以控制循环。
或者,您可以将范围中的所有数字添加到列表中,并shuffle。但是如果你想打印已经尝试的猜测,它会稍微改变一下逻辑。实质上,您需要在每个混洗列表中找到false
的索引。以较低的胜利为准。您可以将每个猜测字符串的sub-list从零打印到相应的正确索引。
答案 1 :(得分:0)
您可以通过限制迭代升级条件。例如,
int maxGame = 100;
int i = 0;
do {
p1 = (rand.nextInt(60 - 50) + 50);
p2 = (rand.nextInt(60 - 50) + 50);
...
i++;
} while (i<maxGame && p1 != a && p2 != a);
答案 2 :(得分:0)
如果玩家已经拥有该随机数,您可以生成一个新的随机数:
ArrayList myArray = new ArrayList();
ArrayList secArray = new ArrayList();
Random rand = new Random();
int p1;
int p2;
do {
p1 = (rand.nextInt(60 - 50) + 50);
while (myArray.contains(p1))
{
p1 = (rand.nextInt(60 - 50) + 50);
}
p2 = (rand.nextInt(60 - 50) + 50);
while (secArray.contains(p2))
{
p2 = (rand.nextInt(60 - 50) + 50);
}
myArray.add(p1);
secArray.add(p2);