gpt4 book ai didi

java - 类(class)测试代码中出现 NullPointerException?

转载 作者:行者123 更新时间:2023-12-01 19:33:54 26 4
gpt4 key购买 nike

所以测试我的练习的代码给了我失败测试:

"nullpointerException,在调用 addPlayer(Player: Atro, 0) 时。导致失败的代码 Team j = new Team("HIFK"); Player p = new Player("Atro"); j.addPlayer(p) ;

我已经在我的主程序中运行了这段代码,它运行得很好,所以我不明白为什么测试代码有问题。

public class Main {
public static void main(String[] args) {
Team barcelona = new Team("FC Barcelona");
barcelona.setMaxSize(16);
Player brian = new Player("Brian");
Player pekka = new Player("Pekka", 39);
barcelona.addPlayer(brian);
barcelona.addPlayer(pekka);
barcelona.addPlayer(new Player("Mikael", 1));

System.out.println("Total goals: " + barcelona.goals());
}

}

import java.util.ArrayList;

public class Team {
private String name;
private ArrayList<Player> playersOnTeam = new ArrayList<>();
private int maxSize;


public Team(String teamName) {
name = teamName;
}

public String getName() {
return name;
}

public void addPlayer(Player playerToAdd) {
if (playersOnTeam.size() == maxSize) {
return;
}
playersOnTeam.add(playerToAdd);
}

public void printPlayers() {
String playerList = "";
for (Player i : this.playersOnTeam) {
System.out.println(i.getName() + ", " + "goals " + i.goals());
}
}

public void setMaxSize(int setSize) {
maxSize = setSize;
}

public int size() {
return playersOnTeam.size();
}

public int goals() {
int allGoals = 0;
for (Player i : playersOnTeam) {
allGoals = allGoals + i.goals();
}
return allGoals;
}

}

public class Player {
private String playerName;
private int goals;

public Player(String name) {
this(name,0);
}

public Player(String name, int score) {
playerName = name;
goals = score;
}

public String getName() {
return this.playerName;
}

public int goals() {
return goals;
}

public String toString() {
return "Player: " + playerName + ", " + "Goals " + goals;
}

}

最佳答案

您需要初始化playersOnTeam

private ArrayList<Player> playersOnTeam = new ArrayList<>();

如果没有初始化,playersOnTeam将为null(并且无法使用.add()访问

关于java - 类(class)测试代码中出现 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58522538/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com