我的模型类中的nameA = view.getHumanName(nameB);
行上出现空指针异常。我正在尝试使用视图类中的nameA
方法建立getHumanName
。我还尝试将this.view = view
添加到模型构造函数中,但这并不能解决问题。为什么我在这种情况下会收到此错误?
模型类和实例变量:
public Model(Dice die){
nameB = "Toby";
nameA = view.getHumanName(nameB);
p1 = new Player(nameA);
p2 = new Player(nameB);
this.die = die;
}
}
View类中的方法:
public String getHumanName(String compName){
System.out.println("Enter a name for the human player: ");
String humanName = scan.nextLine();
while(humanName.equals(compName) || humanName.trim().isEmpty()){
System.out.println("The human player cannot have the same name as the computer player or be blank. Enter a new name for the human player: ");
humanName = scan.nextLine();
}
return humanName;
}
答案 0 :(得分:2)
您永远不会为查看分配任何内容,因此默认情况下它会初始化为null。尝试在构造函数中添加以下内容:
view = new View();