【发布时间】:2014-02-23 21:29:28
【问题描述】:
所以我有一个名为 PlayingCard 的类,它创建一个包含 int rank 和 int suit 的对象(以模拟扑克牌)。
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 张卡片,每张卡片都有自己的套装/等级组合来创建一副卡片。
【问题讨论】:
-
数组索引没有也不能有名字。数组索引使用数字访问。