我有一个程序可以生成一副扑克牌并显示七张随机牌。我试图将选中的七张牌传递给一个字符串,但我只知道如何将整个数组设置为一个字符串,而不仅仅是所选的7张牌。
public class PlayedCards{
public static void main(String[] args){
int[] deck = new int[52];
String[] suits = {"Spades", "Clubs", "Diamonds", "Hearts"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
for (int a = 0; a < deck.length; a++){
deck[a]= a;
}
for (int a = 0; a <deck.length; a++){
int order = (int)(Math.random() * deck.length);
int temp = deck[a];
deck[a] = deck[order];
deck[order] = temp;
}
for (int a = 0; a < 7; a++){
String suit = suits[deck[a] / 13];
String rank = ranks[deck[a] % 13];
System.out.println(rank + " of " + suit);
}
System.out.println(rank + " of " + suit);
}
}
我的问题是:
我的阵列中显示的值是否为0-6?
如果是这样,我如何将数组的这些值设置为一个单独的字符串,然后我可以回想起该用户正在播放?
答案 0 :(得分:1)
如果您只想创建代表播放器播放内容的String
,请直接将每种卡片类型和数字连接到结果String
(隐式创建新的String
在每个连接上)或者更好的是,使用StringBuilder
来做到这一点,并在最后转换为String
。像这样:
StringBuilder sb = new StringBuilder();
for (int a = 0; a < 7; a++) {
...
sb.append(a+1).append(": ").append(rank).append(" of ").append(suit).append("\n");
...
String playedCards = sb.toString();
System.out.println(playedCards);
答案 1 :(得分:0)
更好地创建一个不可变的卡片类
class Card
{
private final int m_suit;
private final int m_rank;
public Card( int suit, int rank )
{
m_suit = suit;
m_rank = rank;
}
public int getSuit()
{
return m_suit;
}
public int getRank()
{
return m_rank;
}
}
现在您可以创建卡实例并将其传递或存储在ArrayList中。对于例如
Card card1 = new Card( deck[a] / 13, deck[a] % 13);
System.out.println( rank[card1.getRank()] + " of " + suit[card1.getSuit()]);
答案 2 :(得分:0)
public class PlayCards {
public static void main(String[] args) {
int[] deck = new int[52];
String[] suits = { "Spades", "Clubs", "Diamonds", "Hearts" };
String[] ranks = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"Jack", "Queen", "King" };
for (int a = 0; a < deck.length; a++) {
deck[a] = a;
}
for (int a = 0; a < deck.length; a++) {
int order = (int) (Math.random() * deck.length);
int temp = deck[a];
deck[a] = deck[order];
deck[order] = temp;
}
Card card = null;
Card[] cards = new Card[7];
for (int a = 0; a < 7; a++) {
card = new Card(suits[deck[a] / 13], ranks[deck[a] % 13]);
cards[a] = card;
}
Player player = new Player();
player.showCards(cards);
}
}
class Card {
private String suit;
private String rank;
public Card(String suit, String rank) {
this.suit = suit;
this.rank = rank;
}
public String toString() {
StringBuilder card = new StringBuilder();
card.append(this.rank);
card.append(',');
card.append(this.suit);
return card.toString();
}
}
class Player {
public void showCards(Card[] cards) {
for (int a = 0; a < 7; a++) {
System.out.println(cards[a].toString());
}
}
}