2011-06-29 13 views
0

私はjavaでいくつかのプロジェクトに取り組んでいます。 ここで私はこの問題に悩まされ、どこに間違っているのか理解できません。nullポインタの例外

私は2つのクラス: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"; 

あなたはすぐにそれに要素を設定するためには、NULLである、間接参照aしようとしています。私はある種のListを使用することをお勧めします(あなたが行う場合でも、多くの場合と)あなたがそれを取り込む開始する前に、あなたのコレクションが持つべき要素の数がわからない場合

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

:あなたは配列を初期化する必要があります。 - あなたがすべてでwhileループに入るならば、それは常に 0になりますので、あなたは決してi変更しないいる

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

:あなたはここで別の問題を抱えている

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

注:たとえば、 、あなたはそれから出ることはありません。

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

またはそれ以上:

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

Gees Jon!あなたはすでに私を打つ? –

4

あなたはこのような何かをしたいですあなたは将来どのような問題を見つけるか考えています。 java api docからは、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

彼らが与えるnullポインタ例外のあなたはおそらく定義の問題を強調した:これは問題です

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

パッケージテスト;

パブリッククラス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]); 
      i++; 
     } 
    } 

}

パッケージテスト。

パブリッククラス子{将来的には

public String[] main() { 

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

}