Java - 创建了一副牌,发了五张现在需要判断手牌中是否包含一对

Java - Created a deck of cards, dealt five now need to determine whether the hand contains a pair

正如主题可能解释的那样,我需要弄清楚发给玩家的五张牌中是否有任何一张被认为是一对,如果有一对,它将作为最终 JOptionPane 的一部分打印到状态 "You have a pair of [pair]" 有没有一种方法可以按照我当前设置琴弦的方式来做到这一点,或者它们不会被识别为成对,因为它们永远不会是同一花色...

感谢您的帮助。

这是我现在的代码:

       int cardsPerPlayer = 5;
   int players = 1;


      String[] suit = {" of Spades", " of Diamonds", " of Clubs", " of Hearts"};
      String[] face = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
      String [] deck = new String[52];

      for (int i = 0; i < deck.length; i++){
         deck [i] = face[i%13] + suit[i/13];
         //System.out.println(deck[i]);
      }
      for (int i = 0; i <deck.length; i++){
      int index = (int) (Math.random()*deck.length);

      String temp = deck[i];
      deck[i] = deck[index];
      deck[index] = temp;
      }
      for (String u: deck) {
      //System.out.println(deck);
   }
   StringBuilder sb = new StringBuilder();
           for (int i = 0; i < players * cardsPerPlayer; i++) {
            sb.append(deck[i])
            .append("\n");
        }
   JOptionPane.showMessageDialog(null, sb.toString());
}
}

这可能不是最优雅的解决方案,但它会起作用:

//Create an array with an integer for all the different faces
int[] amount = new int[face.length];

//set all those values to 0
for(int i = 0; i < amount.length;i++) amount[i] = 0;

//loop through the five cards
for(int i = 0; i < cardsPerPlayer;i++) {

    //setting the faceIndex to 0, which will later be used to see what face it is (so if its a 2 it will have face 0, just like the array
    int faceIndex = 0;

    //looping through all the faces
    for(int j = 0; j < face.length;j++)  {

        //detecting if the jth item in the face array matches the first character of the current card
        if(face[j].equals(Character.toString(deck[i].charAt(0)))) {
            //make the faceIndex that number
            faceIndex = j;
        }
    }

    //so now faceIndex is the index of the face in the array
    //so if the face is 2, faceIndex is 0
    //if the face is K, the faceIndex is 11 etc.
    //we add one to that item in the amount array
    amount[faceIndex]++;
}
//now we know how much of each face is in the dealt cards
//looping through all the amounts of cards
for(int i = 0; i < amount.length; i++) {
    //if the amount of cards with the current face is 2, we have a pair! (which we print)
    if(amount[i] == 2) {
        System.out.println("You have a pair of " + face[i] + "s!");
    }
}

如果你想使一对也包含超过 2 张相同的面孔,你应该将 if(i == 2) { 更改为 if(i >= 2) {