我是第一位Java學生,當創建一個隨機從標準52卡片組中選擇兩張卡片的程序時遇到了一個小問題。我試圖創建一個聲明,比較兩張牌是否有相同的等級或相同的花色。當我嘗試創建一個if語句時,我得到一個錯誤,說我無法比較兩個相同的表達式。我想知道是否有人可以給我一些關於如何做的見解。這是我的代碼:如何比較Java卡程序中隨機生成的卡片?
package Assignment3;
public class HouseOfCards {
public static void main(String[] args) {
int[] deck = new int[52];
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
for(int i = 0; i < deck.length; i++) deck[i] = i;
for(int i = 0; i < deck.length; i++) {
int index = (int)(Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
for(int i = 0; i < 2; i++) {
String suit = suits[deck[i]/13];
String rank = ranks[deck[i] % 13];
System.out.println(rank + " of " + suit);
}
}
}
我的嘗試是:
if (suit==suit)
System.out.println("Cards share the same suit");
else
System.out.println("Cards do not share the same suit");
if (rank==rank)
System.out.println("Cards share the same rank");
else
System.out.println("Card do not share the same rank");
您能否包含您的嘗試? – Szymon
if(suit == suit) \t \t \t System.out.println(「Cards shared same suit」); \t \t else \t \t \t System.out.println(「Cards does not share same suit」); \t \t if(rank == rank) \t \t \t System.out.println(「Cards sharing the same rank」); \t \t else \t \t \t System.out.println(「卡不共享相同的等級」); – arry617