我不明白为什么当我尝试向 a1[i] 数组添加值时会出现空指针异常。
public class Array {
String text;
int total = 0, count = 0;
Array[] a1 = new Array[100];
Scanner scan = new Scanner(System.in);
public void setData() {
int i=0;
System.out.println(a1.length);
do {
System.out.println("Enter some data: ");
text = scan.next();
if (text.equals("end"))break;
a1[i].text = text; //I get a null pointer exception here. Not sure why.
i++;
} while (true);
}
最佳答案
a1
数组中初始化的所有内容都是 null
。在使用成员方法执行任何操作之前,您必须将 Array()
的新实例放入其中。
这意味着:每次您想要对 a1[i]
执行某些操作时,您都必须首先在其中拥有一个新的 Array
实例。
示例:
for(int i = 0; i < n; i++) {
a1[i] = new Array();
}
关于Java - 为什么我会收到此 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9968336/