编写一个程序,从一副52张(不包含大王和小王)的牌中随机选出4张牌。要求输出随机4张牌的花色和号码。 提示:定义对象数组
时间: 2024-10-08 11:25:24 浏览: 59
当你想要编写这样的程序时,首先需要创建一个表示牌的对象类,包括花色和点数两个属性。然后,你可以使用Java的`java.util.Random`类生成随机数,并结合数组和ArrayList来存储和抽取四张牌。以下是一个简单的示例:
```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
// 定义牌的类
class Card {
String suit; // 花色 (例如 "Hearts", "Diamonds", "Clubs", "Spades")
int rank; // 点数 (2~10, J, Q, K, A)
public Card(String suit, int rank) {
this.suit = suit;
this.rank = rank;
}
@Override
public String toString() {
return suit + " of " + rank;
}
}
public class Main {
public static void main(String[] args) {
List<Card> deck = createDeck();
Random random = new Random();
List<Card> selectedCards = selectRandomCards(deck, 4);
for (Card card : selectedCards) {
System.out.println(card.toString());
}
}
// 创建52张牌的数组
private static List<Card> createDeck() {
String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};
int[] ranks = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
List<Card> deck = new ArrayList<>();
for (int i = 0; i < suits.length; i++) {
for (int j = 0; j < ranks.length; j++) {
deck.add(new Card(suits[i], ranks[j]));
}
}
return deck;
}
// 随机选择指定数量的卡片
private static List<Card> selectRandomCards(List<Card> deck, int count) {
if (count > deck.size()) {
throw new IllegalArgumentException("Cannot select more cards than available in the deck.");
}
List<Card> selected = new ArrayList<>(count);
while (selected.size() < count) {
int index = random.nextInt(deck.size());
selected.add(deck.remove(index));
}
return selected;
}
}
```
这个程序会随机抽取并打印出四张牌的花色和号码。运行多次可以看到不同的组合。
阅读全文