nullPointerException, but doesn't look wrong to me
Hi, little code problem
Code java:
public void display() {
for (int i = 0; i < 25; i++) {
StringBuilder line = null;
for (int j = 0; j < 25; j++) {
line.append(puzzleArray[i][j]); //this is line 20
}
System.out.println(line.toString()); //this line seems linked to the error.
}
}
The problem I got was:
#
Exception in thread "main" java.lang.NullPointerException
at prog4.Puzzle.display(Puzzle.java:20)
at prog4.Prog4.main(Prog4.java:8)
meanwhile when I tried the following (not what I wanted but similar there wasn't a problem)
Code java:
public void display() {
for (int i = 0; i < 25; i++) {
for (int j = 0; j < 25; j++) {
System.out.println(puzzleArray[i][j]);
}
}
}
Re: nullPointerException, but doesn't look wrong to me
What variable on line 20 has a null value? Find the variable and backtrack in the code to see why the variable does not have a valid value.
Where do you assign a non-null value to the line variable after you give it a null value?
Re: nullPointerException, but doesn't look wrong to me
Code :
StringBuilder line = null;
for (int j = 0; j < 25; j++) {
line.append(puzzleArray[i][j]); //this is line 20
You set the string builder line to null, and then, a couple of lines later in the loop you try and call its append() method. You will always get a NullPointerException when you call a method on something that is null. (That's basically what the exception means.)
Try initialising line to a non null value.