0

so the code that tests my exercises is giving me the fail test of:

"nullpointerexception, in call addPlayer(Player: Atro, 0). Code that caused the failure Team j = new Team("HIFK"); Player p = new Player("Atro"); j.addPlayer(p);

I've ran this code in my main and it works just fine so I dont understand why the testcode has a problem.

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;
}

}

28gizmo
  • 3
  • 1
VeryJazzy
  • 45
  • 6

1 Answers1

3

You need to initialize playersOnTeam

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

Without initialization, the playersOnTeam will be null (and can't be access with .add()

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Ori Marko
  • 56,308
  • 23
  • 131
  • 233