[英]How do I compare values in parallel arrays to eliminate duplicates?
我正在創建一個程序來處理一副牌中的 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 語句也永遠不會評估為真,所以我不能去更換重復的卡片。
代碼背后的邏輯看起來不錯。 我認為您只是在后面的 for 循環中犯了一個小錯誤。 我認為 if 語句中的條件應該是
(suit[x] == suit[c]) && (value[x] == value[c])
代替
(suit[x] == suit[c]) && (value[x] == suit[c])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.