带有枚举的卡应用程序返回null

时间:2013-11-08 16:11:29

标签: java enums

正如标题所说,我正在试验Enums,但我的输出完全错误。而不是获得卡套装和排名我得到两个空值。

有人指出我正确的方向吗?

卡片类

public class Card {



    private Suit suit;
    private Rank rank;



    public Card (Suit suit, Rank rank) {

    }

    public Suit getSuit(){
        return suit;
    }

      public void setSuit(Suit suit)
    {
    this.suit = suit;
    }

    public Rank getRankValue()
    {
    return rank;
    }

    public void setRankValue(Rank rank)
    {
    this.rank = rank;
    }


    @Override
    public String toString ( ) { return ( rank + " of " + suit ); }

    }

手课

public class Hand {

private Card theCards[ ];
private int numCards;
private static final int max = 5;

public Hand ( )
{
 theCards = new Card [max];
 numCards = 0;
}
public void addCard( Card aCard ) 
{ 
     if (numCards < max) theCards[numCards++] = aCard; 
}
@Override
public String toString ( ) 
{
   String s = ""; 
   for (int i = 0; i < numCards; ++i)  { 
    s += "\n" + theCards[i]; 
   }
   return s;
}
}

排名等级

public enum Rank {

ACE(1),
TWO(2),
THREE(3),
FOUR(4),
FIVE(5),
SIX(6),
SEVEN(7),
EIGHT(8),
NINE(9),
TEN(10),
JACK(10),
QUEEN(10),
KING(10);

private int rank;

private Rank (int value)

{
 this.rank = value;
}

public int getRankValue() {

return rank;
}
}

适合班级

public enum Suit {

HEARTS , SPADES , CLUBS , DIAMONDS 
}

我的班级用于创建卡片并调用toString。

public class HandDriver {

public static void main( String[] args ){ 

Card c1 = new Card(Suit.valueOf("HEARTS"),Rank.valueOf("TEN"));
System.out.print (c1.toString());
}
}

1 个答案:

答案 0 :(得分:5)

public Card (Suit suit, Rank rank) {

}

问题不在于枚举,但在构造函数中,你实际上什么都不做。您将SuitRank作为参数,但不将它们保存在局部变量中。与下面的代码一样,您需要使用通过构造函数获得的参数来分配本地实例变量的值。

public Card (Suit suit, Rank rank) {
   this suit = suit;
   this.rank = rank;
}