当我尝试调用addPlayer方法时,下面的类一直给我一个空指针,我不知道我做错了什么。 :请记住这是非常简单的东西......据说......我正在学习Java。
import java.util.*;
public class Team {
private String teamName;
private ArrayList<Player> players;
private int numberOfPlayers;
public Team(String teamName) {
this.teamName = teamName;
}
public String getName() {
return this.teamName;
}
public void addPlayer(Player player) {
this.players.add(player);
}
public void printPlayers() {
for (Player player : this.players) {
System.out.println(player);
}
}
}
这是Player类:
public class Player {
private String name;
private int goals;
public Player(String name) {
this.name = name;
}
public Player(String name, int goals) {
this.name = name;
this.goals = goals;
}
@Override
public String toString() {
return this.getName() + ", goals " + this.goals();
}
public String getName () {
return this.name;
}
public int goals() {
return this.goals;
}
}
答案 0 :(得分:8)
这是你的问题:
private ArrayList<Player> players;
未初始化,在实例化类时永远不会创建新的。
将以下内容添加到构造函数中:
public Team(String teamName) {
this.teamName = teamName;
this.players = new ArrayList<Player>();
}
答案 1 :(得分:6)
您尚未初始化变量,因此其值为null。
private ArrayList<Player> players = new ArrayList<Player>();
那应该解决它。
答案 2 :(得分:2)
你已经声明了一个ArrayList但初始化在哪里? 通过将ArrayList初始化为:
来修复它private ArrayList<Player> players = new ArrayList<Player>();