2015-11-04 57 views
2

我是第一位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"); 
+0

您能否包含您的嘗試? – Szymon

+0

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

回答

1

如果要比較的第2張卡,以檢查它們是否具有相同的西裝或等級,你可以使用下面的代碼。您不需要循環,只需比較陣列中索引爲0和1的卡即可:

if (deck[0]/13 == deck[1]/13) { 
    System.out.println("Cards share the same suit"); 
} else { 
    System.out.println("Cards do not share the same suit"); 
} 
if (deck[0] % 13 == deck[1] % 13) { 
    System.out.println("Cards share the same rank"); 
} else { 
    System.out.println("Card do not share the same rank"); 
} 
+0

我在哪裏可以在我的代碼中執行此操作? – arry617

+0

而不是'for(int i = 0; i <2; i ++){'loop。 – Szymon

+0

但是我不需要循環打印出兩張隨機卡嗎? – arry617

相關問題