【问题标题】:How do I compare values in parallel arrays to eliminate duplicates?如何比较并行数组中的值以消除重复项?
【发布时间】:2020-02-26 23:17:14
【问题描述】:

我正在创建一个程序来从一副牌中随机发 5 张牌,同时确保没有重复发牌,仅使用并行数组。这是我目前所拥有的。

int [] notSuit = {1, 2, 3, 4};
String [] copySuit = {"Clubs", "Diamonds", "Hearts", "Spades"};

int [] notValue = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; 
String [] copyValue = {"2", "3", "4", "5", "6","7", "8", "9", "10", "Jack", "Queen", "King", "Ace"};

String [] verifiedCards = new String[5];

int [] suit = new int[5];
int [] value = new int[5];

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

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

        verifiedCards[i] = copyValue[randVal] + " of " + copySuit[randSuit]; // stores cards in english
    }
}

for (int x = 0; x < suit.length; x++) {
    for (int c = 1; c < suit.length; c++) {
        if ((suit[x] == suit[c]) && (value[x] == suit[c])) {
            System.out.println("Duplicate Spotted!");
        }
    }
}

我正在使用底部嵌套的 for 循环来尝试遍历数组以查找重复项并通过打印出“Duplicate Spotted”来表示它们。问题是,即使处理了重复的卡片,if 语句也永远不会评估为真,因此我无法更换重复的卡片。

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    代码背后的逻辑看起来不错。我认为您只是在后者 for 循环中犯了一个小错误。我认为if语句中的条件应该是

    (suit[x] == suit[c]) && (value[x] == value[c])
    

    而不是

    (suit[x] == suit[c]) && (value[x] == suit[c])
    

    【讨论】:

    • 有些卡片对被检查了不止一次。内循环应该从x+1 开始,外循环应该在x &lt; length - 1 结束。这也将避免 x == c 您的代码当前声称是重复的,但实际上只是一张卡(与其本身相比)。
    猜你喜欢
    • 2014-12-16
    • 2017-12-31
    • 2012-01-31
    • 2021-05-09
    • 1970-01-01
    • 2013-02-02
    • 2020-12-14
    • 1970-01-01
    • 2023-03-24
    相关资源
    最近更新 更多