gpt4 book ai didi

用于选择和比较卡片的 Java 代码(没有 Arraylist)

转载 作者:搜寻专家 更新时间:2023-10-31 20:30:02 25 4
gpt4 key购买 nike

我看到很多与此类似的问题,但它们的答案是我还没有学过的代码。我应该能够在没有数组列表的情况下完成这项任务,这对我来说是一个挑战。我需要玩一场 war 游戏:创建一个卡片类别,创建一个牌组然后随机生成第一张牌,从牌组中“移除”该牌并制作第二张牌以查看哪张牌获胜,继续比较直到甲板已经用完了。这是我目前所拥有的:

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 并没有深入了解,因为我不知道如何展示第一张牌。运行时显示:The card is: [LCard;@4a5ab2random#1如何显示数组中的第一张卡片?我需要帮助弄清楚如何分配第一张卡片和第二张卡片,同时显示它们然后比较它们。我还有很长的路要走,所以一步一个脚印。

最佳答案

最简单的做法是在您的 Card 类中实现一个 toString 方法。

public String toString() {
return String.format("%s of %s", stringValue, cardSuit);
}

当你这样做时,将两个数组(suitvalue)移出构造函数,使它们成为 static final,然后重命名为全大写:

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"};

此外,卡片的选择不应该像您那样完成:

Card[] playerCard = new Card[r];//create the player's card

创建一个 r 卡片数组,并将其分配给 playerCard。这是不正确的:您已经在 Deck 中创建了所有卡片,只需从中随机抽取一张即可:

public Card takeRandomCard() {
int r;
do {
r = (int)(Math.random() * 52);
} while (taken[r]);
taken[r] = true;
return fullDeck[r];
}

注意这里的小补充:taken 是一个包含 52 个 boolean 对象的数组,表示该牌已从牌组中拿走。

这是您的 code with my modifications从上面在 ideone 工作。

关于用于选择和比较卡片的 Java 代码(没有 Arraylist),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10457634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com