Art*_*hur -1 java enums constructor nullpointerexception
我正在使用enum构造函数构建一个 Blackjack 卡类。
当我尝试调用我的构造函数时,我得到了java.lang.NullPointerException.
我已经阅读了一些线程,说它是关于引用的,null但我仍然不明白为什么我会收到这个错误。
请参阅下面的我的代码(它编译,但给出错误)
public class Card {
/**
* each card should have a suit and a rank
*/
// Create enumeration for suits, use our abbreviation as the String value
enum SUIT {
SPADE ("S"),
HEART ("H") ,
CLUB ("C"),
DIAMOND ("D");
// need constructor
private String abbreviation;
private SUIT(String abbreviation) {
this.abbreviation = abbreviation;
}
}
// Create enumeration for ranks with String abbreviation and int value
enum RANK {
ACE ("A", 11), // don't worry about the value of ACE = 1 now, we can work on it later
TWO ("2", 2),
THREE ("3", 3),
FOUR ("4", 4),
FIVE ("5", 5),
SIX ("6", 6),
SEVEN ("7", 7),
EIGHT ("8", 8),
NINE ("9", 9),
JACK ("J", 10),
QUEEN ("Q", 10),
KING ("K", 10);
// need constructor
private String abbreviation;
private int value;
private RANK (String abbreviation, int value) {
this.abbreviation = abbreviation;
this.value = value;
}
}
// instance var
public SUIT suit;
public RANK rank;
// Card constructor, each card should have a suit and a rank
public Card (SUIT suit, RANK rank) {
this.suit = suit;
this.rank = rank;
}
// method to get the name of the card
public String name;
{
name = this.rank.abbreviation + this.suit.abbreviation;
}
public static void main (String[] args) {
SUIT c = SUIT.CLUB;
RANK j = RANK.JACK;
System.out.println(c.abbreviation);
System.out.println(j.abbreviation);
System.out.println(j.value);
Card cd = new Card(c, j);
}
}
Run Code Online (Sandbox Code Playgroud)
原因是你有一个初始化块
// method to get the name of the card
public String name;
{
name = this.rank.abbreviation + this.suit.abbreviation;
}
Run Code Online (Sandbox Code Playgroud)
它在类 Card 被实例化时但在构造函数的代码之前执行。这意味着字段 this.rank 和 this.suit 尚未设置为任何非空值。
如果注释是正确的,并且您确实想定义一个方法而不是一个初始化程序块,则需要像这样重新编写它:
// method to get the name of the card
public String name() {
return this.rank.abbreviation + this.suit.abbreviation;
}
Run Code Online (Sandbox Code Playgroud)