// This code lets the computer select the first random number from your array
int rn1 = boarduser[new Random().nextInt(boarduser.length)];
System.out.println("Computer's Value: " + rn1);
// This code lets the computer select the second random number from your array
int rn2 = boarduser[new Random().nextInt(boarduser.length)];
System.out.println("Computer's Value: "+ rn2);
boolean tokenduplicate1; // check if the computer took the same value twice
for (int j = 0; j < i; ++j) {
if (rn2 == rn1) {
tokenduplicate1 = true;}
while (tokenduplicate1);
// This code lets the computer select the third random number from your array
int rn3 = boarduser[new Random().nextInt(boarduser.length)];
System.out.println("Computer's Value: "+ rn3);
boolean tokenduplicate2; // check if the computer took the same value twice
for (int k = 0; k < i; ++k) {
if (rn3 == rn1 || rn3 == rn2) {
tokenduplicate1 = true;}
while (tokenduplicate1);
首先我想说我对 Java 的了解有限,所以这里是
代码仍然不完整,但我想做的是检查 boarduser
中选择的随机变量是否与之前的值相同。如果是,我希望它在 boarduser
数组中选择另一个变量,直到它与前一个变量不同。
最佳答案
只需继续(重新)选择第二个值,直到它与第一个值不一致为止。
int rn1 = boarduser[new Random().nextInt(boarduser.length)];
System.out.println("Computer's Value: " + rn1);
int rn2 = boarduser[new Random().nextInt(boarduser.length)];
while(rn2 == rn1)
{
rn2 = boarduser[new Random().nextInt(boarduser.length)];
}
System.out.println("Computer's Value: " + rn2);
关于java - 尝试在 Java 中检查重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26807352/