我要创建Card类型的ArrayList
我的Card类将有2个实例类型的实例变量,称为Suit类型,而String类型则称为rank。 Suit类型是其自己的子类,具有2个实例变量,这些实例变量的类型为String,称为suitTitle,类型为Boolean,称为selected。
我的卡类如下
public class Card {
public Suit suit;
public String rank;
有了构造函数以及所有明显的getter和setters
我的西服班看起来像这样
public class Suit {
public String suitTitle;
public Boolean selected;
有了构造函数以及所有明显的getter和setters
创建卡片时,首先我需要一个类似这样的花色数组
Suit[] suit = new Suit[4];
suit[0].suitTitle = "Spades";
suit[1].suitTitle = "Hearts";
suit[2].suitTitle = "Clubs";
suit[3].suitTitle = "Diamonds";
但是当尝试输入值时,我得到了一个nullpointer异常
答案 0 :(得分:3)
执行此操作时:
Suit[] suit = new Suit[4];
...您正在创建一个足以容纳4个Suit
对象的数组,但是该数组中的每个对象均为空。
因此,您需要执行以下操作:
Suit[] suit = new Suit[4];
// put actual Suit objects in the array
suit[0] = new Suit();
suit[1] = new Suit();
suit[2] = new Suit();
suit[3] = new Suit();
suit[0].suitTitle = "Spades";
suit[1].suitTitle = "Hearts";
suit[2].suitTitle = "Clubs";
suit[3].suitTitle = "Diamonds";
答案 1 :(得分:-1)
您正在初始化衣服数组,但是对于数组衣服对象的每个位置为null,因此您将获得NullPointerException。 请检查以下内容:
public class Card {
public Suit[] suit;
public String rank;
}
public class Suit {
public String suitTitle;
public Boolean selected;
}
public class TestCard {
public static void main(String[] args) {
Suit[] suitList = new Suit[4];
Suit suit1 = new Suit();
suit1.suitTitle = "Spades";
suitList[0] = suit1;
Suit suit2 = new Suit();
suit2.suitTitle = "Hearts";
suitList[1] = suit2;
Suit suit3 = new Suit();
suit3.suitTitle = "Clubs";
suitList[2] = suit3;
Suit suit4 = new Suit();
suit4.suitTitle = "Diamonds";
suitList[3] = suit4;
Card card = new Card();
card.rank = "xyz";
card.suit = suitList;
}
}
答案 2 :(得分:-2)
我建议您将西服存储为card类中的1-4,而不是拥有西服类,并建议使用getSuit()函数来返回String。如果您以这样的方式订购西服,就可以轻松地进行比较:更有价值的西服是更大的数字,因为它们已经是整数。
String getSuit(){
if(suit == 1){
return "the suit";
}
...
}