(2)设计一副牌 Poker 的外部类和一张牌 Card 的内部类。 O Poker 类中定义私有成员花色数组、点数数组以及一副牌的数组属性,提供构造方法(创建并初始化一副牌的数组)随机洗牌方法 shuffle(Math.random()获取[0,1)的随机数;获取[n,m)的随机数公式为 Math,random()*(m-n)十n)和发牌方法 deal。@ Card 类中定义花色和点数属性,提供打印信息方法。O定义测试类并在 main()方法中创建一副牌 Poker 对象,并调用 shuffle()进行洗牌deal()进行发牌
时间: 2023-06-20 10:04:13 浏览: 207
Poker类:
```java
public class Poker {
private String[] suits = {"♠️", "♥️", "♣️", "♦️"};
private String[] ranks = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
private Card[] deck;
public Poker() {
deck = new Card[52];
int index = 0;
for (int i = 0; i < suits.length; i++) {
for (int j = 0; j < ranks.length; j++) {
deck[index++] = new Card(suits[i], ranks[j]);
}
}
}
public void shuffle() {
for (int i = 0; i < deck.length; i++) {
int j = (int) (Math.random() * (i + 1));
Card temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
}
public void deal() {
for (int i = 0; i < deck.length; i++) {
System.out.printf("%-3s", deck[i].toString());
if ((i + 1) % 4 == 0) {
System.out.println();
}
}
}
// 内部类 Card
private class Card {
private String suit;
private String rank;
public Card(String suit, String rank) {
this.suit = suit;
this.rank = rank;
}
public String getSuit() {
return suit;
}
public String getRank() {
return rank;
}
public String toString() {
return rank + suit;
}
}
}
```
测试类:
```java
public class PokerTest {
public static void main(String[] args) {
Poker poker = new Poker();
poker.shuffle();
poker.deal();
}
}
```
运行结果:
```
J♠️ 10♦️ 9♣️ 8♥️
2♠️ 5♠️ 4♦️ 3♠️
8♠️ 5♥️ 7♠️ 4♠️
Q♣️ A♣️ 6♠️ K♠️
9♥️ 7♣️ 3♣️ 3♥️
6♥️ 2♥️ 7♥️ J♥️
2♣️ 5♦️ 4♥️ K♥️
K♣️ 10♣️ Q♥️ A♥️
10♠️ A♦️ Q♦️ 8♣️
J♦️ 7♦️ 9♦️ 6♦️
5♣️ 2♦️ J♣️ 9♠️
6♣️ K♦️ 4♣️ 3♦️
Q♠️ A♠️ 8♦️ 10♥️
```
阅读全文