java空指针异常,仅当我尝试数组形式的类型时
我是java新手
这是我第一个真正的项目(纸牌游戏:21点)
我做了一个测试类,并被告知使用打印行来尝试并查明我的问题,但我无法理解为什么空异常不断出现。我没有任何设置为null,我的数组已经用“new”初始化。我也可以发布IO类,但我相当确定问题不在这一范围内
public static void main(String[] args) {
// Initializing just a single player
Player x = new Player();
// Quick test to make sure it reads the initial value of 0
System.out.println(x.getMoney());
// Testing user input using an IO class given
System.out.println("How much would you guys like to play with?(Bet money)");
double y = IO.readDouble();
x.addMoney(y);
System.out.println(x.getMoney());
// Successfully prints out the value y
Player[] total = new Player[4];
total[1].addMoney(y);
System.out.println(total[1].getMoney());
// returns the null pointer exception error
}
这是我的球员课程
package Blackjack;
public class Player {
private Hand hand = new Hand();
private double currentMoney = 0;
private double bet = 0;
public void takeCard(Card h) {
hand.addCardToHand(h);
}
public double getBet() {
return bet;
}
public double getMoney() {
return currentMoney;
}
public void betMoney(double k) {
currentMoney = -k;
bet = +k;
}
public void addMoney(double k) {
currentMoney = currentMoney + k;
}
public void resetBet() {
bet = 0;
}
我可以看出问题可能在我的hand初始化中,但是我不要求从代码的hand部分返回任何东西,这一事实让我相信问题并不在这里
# 1 楼答案
初始化对象数组时,它会被空引用“填充”。所以在这种情况下,
total[1]
将返回null,除非您将一个播放器实例分配给索引1:total[1] = new Player();