我正在用java做一些项目。在这里,我被困在这个问题上,无法找出我哪里出了问题。
我上了两门课:Test和Child。
当我运行代码时,我将得到一个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;
    }
}发布于 2011-06-29 05:20:49
问题是:
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);
}发布于 2011-06-29 05:21:43
这就是问题所在:
String[] a = null;
a[0]="This";发布于 2011-06-29 05:29:27
他们强调了您可能需要定义的空指针异常的问题,这会让您知道将来在哪里和什么地方可以找到这个问题。在java中,它定义了什么是npe以及在什么情况下抛出npe。希望它能帮到你。
在需要对象的情况下,应用程序尝试使用null时引发。其中包括:
* Calling the instance method of a null object.
* Accessing or modifying the field of a null object.
* Taking the length of null as if it were an array.
* Accessing or modifying the slots of null as if it were an array.
* Throwing null as if it were a Throwable value. https://stackoverflow.com/questions/6516072
复制相似问题