gpt4 book ai didi

java - 如何为循环中的对象提供新名称?

转载 作者:行者123 更新时间:2023-12-01 13:21:48 25 4
gpt4 key购买 nike

所以我有一个名为 PlayingCard 的类,它创建一个包含 int 等级和 int 花色的对象(以模拟扑克牌)。

public class PlayingCard 
{
private int rank;
private int suit;


public PlayingCard(int rank1, int suit1) //PlayingCard Constructor
{
rank = rank1;
suit = suit1;
}


public int getRank() //Get method to retrieve value of card Rank
{
if(rank >0 && rank <15)
{
return rank;
}
else
return 0;
}


public String getSuit() //Get method to retrieve value of card Suite
{

while (suit >0 && suit <5)
{
if (suit == 1)
{
return "Clubs";
}
else if (suit == 2)
{
return "Diamonds";
}
else if (suit == 3)
{
return "Hearts";
}
else
{
return "Spades";
}
}

return "Invalid suit";
}


@Override //Overrides default Java toString method
public String toString()
{
String strSuit = "";

switch(suit)
{
case 1: strSuit = "Clubs";
break;
case 2: strSuit = "Diamonds";
break;
case 3: strSuit = "Hearts";
break;
case 4: strSuit = "Spades";
break;
default: strSuit = "Invalid Suit";
break;
}

String output = getClass().getName() + "[suit = " +strSuit + ", rank = "
+rank + "]";

return output;
}


public String format() //Allows individual cards to be displayed in a
{ //Specific format.
String strSuit = "";

switch(suit)
{
case 1: strSuit = "Clubs";
break;
case 2: strSuit = "Diamonds";
break;
case 3: strSuit = "Hearts";
break;
case 4: strSuit = "Spades";
break;
default: strSuit = "Invalid Suit";
break;
}

return rank + " of " + strSuit + ", ";
}

@Override
public boolean equals(Object y) //Method for evaluating Object equality.
{

if (getClass() != y.getClass()) //Checks if both object are from the
{ //Same class.
return false;
}

if (y == null) //Checks if second object is empty or non-existent.
{
return false;
}

PlayingCard other = (PlayingCard) y;
return rank == other.rank && suit == other.suit;
}
}

然后我需要创建一个名为 PackBuilder 的程序,它应该使用我的类模拟构建一副纸牌。

问题是我不确定如何为每个对象指定新名称。我想到了类似的数组:

while(rank < 15)
{
PlayingCard cardDeck[1] = new PlayingCard(rank, suit);
}

但它说 cardDeck 已经定义了(我不确定我是否可能做错了,或者使用数组是否不起作用)

我想要的命名方案就像“card1”“card2”“card3”等等,直到我有 52 张牌,每张牌都有自己的花色/等级组合来创建一副牌。

最佳答案

您正在尝试将 PlayingCard 分配给 cardDeck 数组中的第二个元素(索引 1),每次。此外,cardDeck 数组在 while 循环的每次迭代底部立即被丢弃。它的作用域仅存在于循环内部。

改变这个

while(rank < 15)
{
PlayingCard cardDeck[1] = new PlayingCard(rank, suit);
}

像这样的事情

PlayingCard[] cardDeck = new PlayingCard[52];

int i = 0;
while(rank < 15)
{
cardDeck[i++] = new PlayingCard(rank, suit);
}

为了避免无限循环,请更改

cardDeck[i++] = new PlayingCard(rank, suit);

cardDeck[i++] = new PlayingCard(rank++, suit);

可能还有其他问题,但这是一个很好的开始。

关于java - 如何为循环中的对象提供新名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21974811/

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