2011-06-29 141 views
0

我正在开发一些java项目。 在这里,我被困在这个问题,无法找出我要去哪里错了。空指针异常

我做了两个类: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; 
    } 
} 
+3

未来(甚至现在),你应该清楚地表明该行被抛出异常。该信息在异常的堆栈跟踪中可用。 –

+3

...它按预期工作:它在'child#main()'中创建'NullPointerException' ;-) –

回答

13

这里的问题:

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

你立即试图取消引用a,这是空,要想在它设置的元素。你需要初始化数组:

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); 
} 
+1

Gees Jon!你已经打败了我? –

4

这就是问题所在:

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

他们强调你可能空指针异常的定义问题会给你知道未来什么以及在哪里可以找到问题。从java api文档中,它定义了什么是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. 
0

封装测试;

公共类测试{

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]); 
      i++; 
     } 
    } 

}

封装测试;

公共类子{

public String[] main() { 

    String[] a = {"This","is","not","Working"}; 
    return a; 

}