我看到很多与此类似的问题,但它们的答案是我还没有学过的代码。我应该能够在没有数组列表的情况下完成这项任务,所以这对我来说是一个挑战。我需要玩一个战争游戏:创建一个卡片类,创建一个牌组,然后随机生成第一张牌,从牌组中“移除”牌并生成第二张牌,看看哪张牌赢了,继续比较直到甲板已经筋疲力尽。这是我到目前为止所拥有的:
public class Card
{
private int cardValue;
private String cardSuit;
private String stringValue;
static final String[] SUIT = {"Clubs", "Diamonds", "Hearts", "Spades"};
static final String[] VALUE = {"Ace","Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
/**
*CONSTRUCTOR for Card class
*contains the arrays for both suit and values
**/
public Card (int cardS, int cardV)
{
cardSuit = SUIT[cardS];
stringValue = VALUE[cardV];
}
/**
*Get method for card suit, access the value of cardSuit
**/
public String getCardSuit()
{
return cardSuit;
}
/**
*get method for card's VALUES
**/
public String getValue()
{
return stringValue;
}
//in order to display string value of cards
public String toString()
{
return String.format("%s of %s", stringValue, cardSuit);
}
}
public class Deck
{
private final int HIGH_SUIT=3;
private final int HIGH_VALUE=12;
int i = 0;
int cardCount;
Card[] fullDeck = new Card[52];
public Deck()
{
for(int s = 0; s <= HIGH_SUIT; s++)
{
//for loop to determine the suit
for (int v = 0; v <= HIGH_VALUE; v++)
{
//construct all 52 cards and print them out
fullDeck[i] = new Card(s, v);
cardCount = (i + 1);
i++;//increment the card counter
}
}
}
}
public class War3
{
public static void main(String[] args)
{
int i=0;
Deck[] fullDeck = new Deck[52]; //set up the deck
//create a random value for the first card
int r = ((int) (Math.random() * 100) % 51);//create random number
Card[] playerCard = new Card[r];//create the player's card
System.out.println("The card is: " + playerCard.toString());
}
如你所见,我在 War 3 中并没有走得太远,因为我不知道如何显示第一张卡片。运行时显示:卡片为:[LCard;@4a5ab2random#1 如何显示数组中的第一张卡片?我需要帮助弄清楚如何分配第一张卡和第二张卡,显示它们然后比较它们。我还有很长的路要走,所以一步一步走。