DeckofCards类
import java.util.Random;
public class DeckOfCards
{
public int suit;
public int card;
public Random r;
public final int MAXSUIT = 3;
public final int MAXCARD = 12;
/**
* Constructor for objects of class DeckOfCards
*/
public DeckOfCards()
{
// initialise instance variables
r = new Random();
shuffleDeck();
}
public void shuffleDeck()
{
suit = r.nextInt(MAXSUIT);
card = r.nextInt(MAXCARD);
}
public int getCard()
{
return card;
}
public int getSuit()
{
return suit;
}
}
卡类
import java.util.Random;
public class Card
{
private DeckOfCards myDeck;
public int card;
public int suit;
public String cardName;
public String suitName;
public Card()
{
card = new myDeck.getCard();
suit = new myDeck.getSuit();
}
public String showCard()
{
return (cardName+ " of "+suit);
}
public void changeCard()
{
new Card();
}
public String getCardName()
{
return cardName;
}
public String getSuitName()
{
return suitName;
}
public void setCardName()
{
switch(card)
{
case 0 :
cardName = "2";
break;
case 1 :
cardName = "3";
break;
case 2 :
cardName = "4";
break;
case 3 :
cardName = "5";
break;
case 4 :
cardName = "6";
break;
case 5 :
cardName = "7";
break;
case 6 :
cardName = "8";
break;
case 7 :
cardName = "9";
break;
case 8 :
cardName = "10";
break;
case 9:
cardName = "Jack";
break;
case 10 :
cardName = "Queen";
break;
case 11 :
cardName = "King";
break;
case 12 :
cardName = "Ace";
break;
default :
}
}
public void setSuitName()
{
switch(suit)
{
case 0 :
suitName = "Diamonds";
break;
case 1 :
suitName = "Hearts";
break;
case 2 :
suitName = "Spades";
break;
case 3 :
suitName = "Clubs";
break;
default :
suitName = "No suit";
break;
}
}
}
答案 0 :(得分:3)
您在初始化之前使用myDeck
。它必须是:
public Card() {
myDeck = new DeckOfCards();
card = myDeck.getCard();
suit = myDeck.getSuit();
}
作为旁注,不需要维护另外两个成员(card
和suit
),因为您可以从myDeck
变量中获取此数据。
您还应该重新考虑您的设计,因为DeckOfCard
应该依赖于Card
类,否则。目前,每当您创建Card
对象时,也会创建另一个DeckOfCards
。这在语义上是错误的。
如果我是你,我会将两个类放在一个包中并使用Card
修饰符装饰protected
构造函数,以便它只能在此包中实例化。另外,我会从myDeck
课程中删除Card
成员,并在Set<Card>
课程中介绍DeckOfCards
成员。
答案 1 :(得分:0)
在设计可以改进的提示中添加一些内容。如果有人认为这不应该在这里:评论,我会立即将其删除。 - 人们通常做的是创建一个Deck作为52 Card对象的Collectíon:
class Card {
Suit suit;
Rank rank;
Card( Suit suit, Rank rank ){...}
}
class Deck {
List<Card> cards = ...
Deck(){
for( Suit suit: EnumSet.allOf(Suit.class) ){
for( Rank rank: EnumSet.allOf(Rank.class) ){
cards.add( new Card( suit, rank ) );
}
}
}
}
你可以在交手前洗牌。