gpt4 book ai didi

java - 枚举返回 null 的卡应用程序

转载 作者:行者123 更新时间:2023-12-01 17:19:20 24 4
gpt4 key购买 nike

正如标题所说,我正在尝试枚举,但得到的输出完全错误。我没有得到卡牌的花色和等级,而是得到了两个空值。

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

卡片类

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
}

还有我的类(class),用于创建卡片并调用 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());
}
}

最佳答案

public Card (Suit suit, Rank rank) {

}

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

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

关于java - 枚举返回 null 的卡应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19863604/

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