如果条件为真,则if-else语句的计算结果不为真

时间:2020-02-27 16:59:06

标签: java arrays if-statement

我正在尝试创建一个程序,该程序从一副纸牌中抽取5张随机纸牌并将西服和值存储在2个并行阵列中,然后我必须检查是否有重复的纸牌并重新绘制它们是否重复。为此,我编写了以下代码:

        for (int i = 0; i < suit.length; i++) {
            for (int j = 0; j < 5; j++) {
                randSuit = rand.nextInt(notSuit.length);
                randValue = rand.nextInt(notValue.length);

                suit[i] = notSuit[randSuit];
                value[i] = notValue[randValue];

                firstCards[i] = copyValue[randValue] + " of " + copySuit[randSuit];
            }        
    }

    for (int i = 0; i < suit.length; i++) {
        for (int j = 1; j < 5; j++) {
            if ((suit[i] == suit[j]) && (value[i] == value[j])) { // this if statement will not evaluate to true even when the conditions are true
                randSuit = rand.nextInt(notSuit.length);
                randValue = rand.nextInt(notValue.length);

                suit[i] = notSuit[randSuit];
                value[i] = notValue[randValue];

                verifiedCards[i] = copyValue[randValue] + " of " + copySuit[randSuit];
            }
        }        
    }

底部2个for循环用于查看卡是否重复,如果重复,则重画该卡并将其存储在verifyCards数组中。而是,它没有运行,并且没有值被放入verifyCards []中。

所以我的问题是,即使有重复项也不会重新绘制。

示例输出:

未验证 俱乐部7 黑桃皇后 俱乐部7 黑桃7 黑桃王牌

已验证 空值 空值 空值 空值 空

如图所示,“ Clubs”中有7个是重复的,该卡应该已经被重新抽签了,但事实并非如此,我不知道为什么。
谢谢。

编辑:西服和值是长度为5的int数组。

2 个答案:

答案 0 :(得分:1)

因此,当您比较两个不是对象的事物时,使用==运算符将比较这些值。但是,就像比较两个字符串时一样,您使用String.equals("hello")而不是String == "hello"

当您将对象与==进行比较时,您在比较的是存储分配,而不是值。您的程序将检查是否在找到对象Y的位置找到了对象X。

因此,要修复程序,您只需要更改比较参考值的方式即可。

答案 1 :(得分:0)

问题在于if条件最后不包含“ && i!= j”,因为这会引起问题。感谢大家的投入!