Java – NullPointerException when accessing array in class
•
Java
I am new to this forum and Java The following code compiles, but when I try to enter a value for a variable, I get NullPointerException What's up?
class output_harm { public int[] timestamp; public int[] state; public output_harm(){ timestamp = new int[8]; state = new int[8]; } } output_harm[][] outputs = new output_harm[7][6]; outputs[0][0].state[0] = 0; //java.lang.NullPointerException
Solution
problem
This is just initializing an array When you call the constructor output_ When harm(), it only initializes state = new int [8]; The state here is initialized in the constructor and results in NullPointerException
Solution: first of all, you need to create a_ Harm initializes an object (if you need to initialize the entire array)
output_harm[][] outputs = new output_harm[7][6]; for(int i=0;i<7;i++){ for(int j=0;j<6;j++){ outputs[i][j] = new output_harm(); } } outputs[0][0].state[0] = 1;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码