Java_扑克牌发放

Java编程练习,实现扑克牌随机发放给四个人

要求

请定义一个名为Card的扑克牌类,该类有两个private访问权限的字符串变量face和suit;分别描述一张牌的牌面值(如:A、K、Q、J、10、9、……3、2等)和花色(如:“黑桃”、“红桃”、“梅花”、“方块”);定义Card类中的public访问权限的构造方法,为类中的变量赋值;定义protected访问权限的方法getFace(),得到扑克牌的牌面值;定义protected访问权限的方法getSuit(),得到扑克牌的花色;定义方法toString(),返回表示扑克牌的花色和牌面值字符串(如“红桃A”、“梅花10”等)。

编写应用程序的main方法中,定义字符串数组f和s;分别表示扑克牌的牌面值和花色;定义52个元素的Card类型数组deck,用来存放4个花色的52张牌。如下所示。
String f[] = {“A”,”2″,”3″,”4″,”5″,”6″,”7″,”8″,”9″,”10″,”J”,”Q”,”K”};
String s[] = {“黑桃”,”红桃”,”梅花”,”方块”};
Card deck = new Card[52];

使用Card类的构造方法给deck数组的52张牌赋值,要求数组中先存放黑桃花色的A、2、3、……、K;然后是红桃花色的A、2、3、……、K;梅花花色的A、2、3、……、K;方块花色的A、2、3、……、K。请写出实现上述功能的程序段。

  1. 请编写模拟洗牌的完整程序,即把数组deck中的扑克牌随机打乱存放顺序,把牌分发给4个人。

参考

代码

import java.util.Random;

public class test2_2 {
  public static void main(String[] args) {
    final int cardNumber = 52;
    // 初始化牌库
    String[] f = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
    String[] s = { "黑桃", "红桃", "梅花", "方块" };
    Card[] deck = new Card[cardNumber];
    int i = 0;
    for (String suit : s) {
      for (String face : f) {
        deck[i] = new Card(face, suit);
        ++i;
      }
    }
    // 打乱牌库
    Card exchangeTemp;
    Random rand = new Random();
    for (int p = 0; p < deck.length; ++p) {
      int targetCard = rand.nextInt(cardNumber - 1);
      exchangeTemp = deck[p];
      deck[p] = deck[targetCard];
      deck[targetCard] = exchangeTemp;
    }
    // 发牌
    PeopleHand A = new PeopleHand();
    PeopleHand B = new PeopleHand();
    PeopleHand C = new PeopleHand();
    PeopleHand D = new PeopleHand();
    i = 0;
    for (Card c : deck) {
      int targetPeople = i % 4;
      switch (targetPeople) {
        case 0:
          A.getCard(c);
          break;
        case 1:
          B.getCard(c);
          break;
        case 2:
          C.getCard(c);
          break;
        case 3:
          D.getCard(c);
          break;
      }
      ++i;
    }
    // 亮牌
    System.out.println("A:" + A.showHandCardString());
    System.out.println("B:" + B.showHandCardString());
    System.out.println("C:" + C.showHandCardString());
    System.out.println("D:" + D.showHandCardString());
  }
}

class Card {
  private String face, suit;

  public Card(String face, String suit) {
    this.face = face;
    this.suit = suit;
  }

  protected String getFace() {
    return face;
  }

  protected String getSuit() {
    return suit;
  }

  public String toString() {
    return suit + face;
  }
}

class PeopleHand {
  Card[] handCards = new Card[13];
  int i = 0;

  void getCard(Card c) {
    handCards[i] = c;
    i++;
  }

  public String showHandCardString() {
    String resoult = "";
    for (Card c : handCards) {
      if (c != null)
        resoult += c.toString() + ",";
    }
    return resoult;
  }
}

此题是random类的使用

Leave a Comment

您的电子邮箱地址不会被公开。 必填项已用*标注