我有一个关于空指针异常的奇怪问题。我在下面发布有问题的代码:
public static void main(String[] args) {
BetHistory testObject = new BetHistory(6);
testObject.addResponse(2, 1, 0); // ERROR HERE
...
}
public class PlayerResponses {
public List<Integer> response;
public PlayerResponses() {
super();
response = new LinkedList<Integer>();
}
...
}
public class BetHistory {
PlayerResponses [][] responses;
int nPlayer;
public BetHistory(int totalPlayers) {
super();
responses = new PlayerResponses[4][totalPlayers];
nPlayer = totalPlayers;
}
public void addResponse(int response, int playerNo, int roundNo)
{
responses[roundNo][playerNo].response.add(response); // DUE TO HERE
}
...
}
提前感谢您的时间。
答案 0 :(得分:3)
在这一行:
responses = new PlayerResponses[4][totalPlayers];
您可以创建一个可以保存对PlayerResponses
个对象的引用的二维数组。您不甚至创建一个PlayerResponses
对象。
您需要在循环中填写(或者稍后根据需要填写):
responses[i][j] = new PlayerResponses();
答案 1 :(得分:0)
这是因为数组中存储的每个public List<Integer> response;
中的PlayerResponses
都没有初始化。
它获得了默认的null
,这就是为什么当您调用add
方法时获得NPE。
答案 2 :(得分:0)
import java.util.*;
public class A {
public static void main(String[] args) {
BetHistory testObject = new BetHistory(6);
testObject.addResponse(2, 1, 0); // ERROR HERE
}
}
class PlayerResponses {
public LinkedList<Integer> response;
public PlayerResponses() {
super();
response = new LinkedList<Integer>();
}
}
class BetHistory {
PlayerResponses [][] responses;
int nPlayer;
public BetHistory(int totalPlayers) {
super();
responses = new PlayerResponses[4][totalPlayers];
for(int i=0;i<totalPlayers;i++) {
responses[0][i] = new PlayerResponses();
responses[1][i] = new PlayerResponses();
responses[2][i] = new PlayerResponses();
responses[3][i] = new PlayerResponses();
}
nPlayer = totalPlayers;
}
public void addResponse(int response, int playerNo, int roundNo)
{
responses[roundNo][playerNo].response.add(response); // DUE TO HERE
}
}