// 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
数组中选择另一个变量,直到它与前一个变量不同。
答案 0 :(得分:1)
保持(重新)选择第二个值,直到它与第一个值不一致。
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);
答案 1 :(得分:0)
您可以使用Set然后检查其长度。
int somevalue = 3; // if you want 3 values
Set<Integer> numbers = new LinkedHashSet<Integer>();
while(numbers.size() != somevalue) {
numbers.add(new Random().nextInt(boarduser.length));
}
System.out.println(numbers);
打印例如:[11,1,5]