gpt4 book ai didi

java - 空指针异常

转载 作者:行者123 更新时间:2023-12-01 06:28:18 24 4
gpt4 key购买 nike

我正在用java做一些项目。在这里我陷入了这个问题,无法弄清楚我哪里出了问题。

我做了两个类(class):TestChild

当我运行代码时,我得到一个 NullPointerException。

package com.test;
public class Test {

child newchild = new child();
public static void main(String[] args) {
new Test().method();
}
void method() {
String[] b;
b = newchild.main();
int i = 0;
while (i < b.length) {
System.out.println(b[i]);
}
}
}
<小时/>
package com.test;
public class child {
public String[] main() {
String[] a = null;
a[0] = "This";
a[1] = "is";
a[2] = "not";
a[3] = "working";
return a;
}
}

最佳答案

问题是这样的:

String[] a = null;
a[0]="This";

您立即尝试取消引用 a(它为 null),以便在其中设置一个元素。您需要初始化数组:

String[] a = new String[4];
a[0]="This";

如果您在开始填充集合之前不知道集合应包含多少个元素(即使您知道),我建议您使用某种List。例如:

List<String> a = new ArrayList<String>();
a.add("This");
a.add("is");
a.add("not");
a.add("working");
return a;

请注意,您在这里还有另一个问题:

int i=0;
while(i<b.length)
System.out.println(b[i]);

你永远不会改变i,所以它总是为0 - 如果你进入while循环,你会永远摆脱不了它。你想要这样的东西:

for (int i = 0; i < b.length; i++)
{
System.out.println(b[i]);
}

或者更好:

for (String value : b)
{
System.out.println(value);
}

关于java - 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6516072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com