我正在尝试将一个简单的插卡放在一起,然后我遇到了NullPointerException,程序编译但是如果我运行它并运行方法setSuit
,我收到此错误消息:
java.lang.NullPointerException
at Cards.setCard(Cards.java:18)
at Cards.<init>(Cards.java:11)
我发布了以下代码并标记了突出显示的区域:
public class Cards {
private String HEARTS = "Hearts";
private String CLUBS = "Clubs";
private String DIAMONDS = "Diamonds";
private String SPADES = "Spades";
private int number;
private String suit;
public Cards(String newCard, int newNumber1) {
setCard(newCard);
setNumber(newNumber1);
}
public void setCard(String newSuit) {
if((suit != null) && // this part get's highlighted
(suit.equalsIgnoreCase(HEARTS)) ||
(suit.equalsIgnoreCase(DIAMONDS)) ||
(suit.equalsIgnoreCase(CLUBS)) ||
(suit.equalsIgnoreCase(SPADES))) {
suit = newSuit;
} else {
suit = "Unknown Suit";
System.out.print("Invalid");
}
}
public int getNumber() {
return number;
}
public String getSuit() {
return suit;
}
public void setNumber(int newNumber) {
number = newNumber;
if(newNumber >0 && newNumber <=10) {
number = newNumber;
}
}
}
答案 0 :(得分:2)
这是一个操作顺序问题。试试这个:
if ((suit != null) && (suit.equalsIgnoreCase(HEARTS) || suit.equalsIgnoreCase(DIAMONDS) || suit.equalsIgnoreCase(CLUBS) || suit.equalsIgnoreCase(SPADES)))
答案 1 :(得分:0)
检查一下,但我认为setCard应该是:
public void setCard(String newSuit)
{
if((newSuit != null) && //this part get's highlighted
(newSuit.equalsIgnoreCase(HEARTS)) ||
(newSuit.equalsIgnoreCase(DIAMONDS)) ||
(newSuit.equalsIgnoreCase(CLUBS)) ||
(newSuit.equalsIgnoreCase(SPADES)))
{
suit = newSuit;
}
else
{
suit = "Unknown Suit";
System.out.print("Invalid");
}
}