0

I have a custom class that includes some array lists, I initialize them in the constructor and then I have a method that adds to these arraylists, but when I run the code, I get this error: java.lang.NullPointerException

public class GameMenu {
private ArrayList<String> player1Moves;
private ArrayList<String> player2Moves;
private ArrayList<String> allMoves;

}

public GameMenu(long limit, Player player1, Player player2) {
    this.player1Moves = new ArrayList<>();
    this.player2Moves = new ArrayList<>();
    this.allMoves = new ArrayList<>();
    System.out.println("test");
}

private void writeDownMoves( Pieces piece , int xCordination , int yCordination ){
    if ( isPlayer1sTurn == true ){
        this.player1Moves.add("**" + piece + piece.getXCordination() + "," + piece.getYCordination() + " to " + xCordination + "," + yCordination + "**");
    //the line above is where the program stops.
    }
    else{
        this.player2Moves.add("**" + piece + piece.getXCordination() + "," + piece.getYCordination() + " to " + xCordination + "," + yCordination + "**");
    }
    this.allMoves.add("**" + piece + piece.getXCordination() + "," + piece.getYCordination() + " to " + xCordination + "," + yCordination + "**");
    piece.setXCrdination(xCordination);
    piece.setYCordination(yCordination);
}

I made sure that I had called the constructor by putting a System.out.println("test"); at the end of that constructor, so while these arraylists are initialized I still get this error. any. ideas about what the problem is?

iman
  • 1
  • 1
  • You're not showing the code that actually causes the exception, so no one can help you. The problem isn't because you didn't initialize the arraylist, but rather, because you're trying to retrieve something that isn't there. The compiler gives you a stack trace showing the exact error and the line number where it occurs. Next time you ask a question, include the stack trace and the bit of code that corresponds with the line number. – MarsAtomic Mar 31 '20 at 03:31
  • I actually put a comment there, but since it was tor clear where it was I changed that comment, thanks for letting me know. – iman Mar 31 '20 at 03:38
  • Can you share the exception details ? I mean which line it's throwing NPE. – Anil Nivargi Mar 31 '20 at 03:41
  • @iman - That comment is not sufficient. You **need** to show us the stacktrace. EDIT the question. (Better still, read the duplink answers to find out how to debug / fix NPEs for yourself.) – Stephen C Mar 31 '20 at 03:43
  • I suspect the problem is that `piece` is `null`. But I also doubt this is the real code, because it is using a variable that has not been declared; i.e. it won't compile ... unless `GameMenu` is a nested class, or there is a static import you are not showing us. – Stephen C Mar 31 '20 at 03:47
  • yes, the piece was actually null, thanks for your comment and helping me. – iman Mar 31 '20 at 04:00

0 Answers0