Java – changing the value of an array through methods in class
•
Java
This is my code:
class Myclass { private static int[] array; public static void main(String[] args) { Myclass m = new Myclass(); for (int i = 0; i < 10; i++) { m.array[i] = i; System.out.println(m.array[i]); } } public Myclass() { int[] array = new int[10]; } }
When it tries to do this, it throws a Java lang.nullPointerException:
m.array[i] = i;
Can someone help me?
Solution
You have declared an array of local variables in the constructor, so you do not actually initialize the array declared in MyClass
You are going to reference the array directly in the constructor replace
int[] array = new int[10];
Use this
array = new int[10];
In addition, you have declared the array static. In the scope of the MyClass class
private static int[] array;
You have only one MyClass instance here, so it doesn't matter, but usually it's not static if you initialize it in the constructor You should delete static:
private int[] array;
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
二维码