java - 尝试在 Java 中检查重复项

标签 java arrays loops

// 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/

相关文章:

android - 在 Kotlin 中更改可变列表中的值

javascript - 从数组中获取 Id 并切换它

java - 如何在 CXF 导管上设置 TLS 参数?

java - 我的Gradle Spring 靴给我一个空的modelAndView对象

java - Hibernate ConstraintViolationException : could not insert, SQL 错误

java - 不能使用列表的元素作为对象构造函数中的参数

javascript - 检查字符串是否包含任何没有正则表达式的字符串数组

loops - 在 O(n) 时间内将数组中的所有元素相互相加

java - 在自定义 gradle 插件中获取类路径依赖

ios - iPhone 应用程序不会将字符串添加到数组,仅限 64 位