2011-08-30 74 views
1

当我运行这段代码,返回数组中的Java

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 


class Posting 
{ 
    String title; 
} 

public class Test 
{ 
    Posting[] dew() 
    { 
     Posting[] p = new Posting[100]; 
     for(int i = 0; i <p.length; i++) 
     { 
      p[i].title = "this is " + i; 
     } 
     return p; 
    } 

    public static void main(String args[]) 
    { 
     Test t = new Test(); 
     Posting[] out = t.dew(); 

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

我得到这个错误, 运行:

Exception in thread "main" java.lang.NullPointerException 
    at mistAcademic.javaProject.newsBot.core.Test.dew(Test.java:20) 
    at mistAcademic.javaProject.newsBot.core.Test.main(Test.java:29) 
Java Result: 1 
BUILD SUCCESSFUL (total time: 1 second) 

莫非你有什么想法?

+0

数组是空的。未创建发布对象如何访问其标题字段 – KDjava

回答

11

您必须在设置字段之前初始化数组元素。

p[i] = new Posting(/* ... */); 
// THEN set the fields 
p[i].title = /* ... */; 
9
Posting[] p = new Posting[100]; 

这只会创建数组本身,所有项都设置为null

所以你需要创建实例并将它们放入数组中。

for(int i = 0; i <p.length ; i++) 
    { 
     p[i] = new Posting(); // <= create instances 
     p[i].title = "this is " + i ; 
    } 
4

你必须初始化你的帖子

Posting[] dew() 
    { 
     Posting[] p = new Posting[100]; 

     for(int i = 0; i <p.length ; i++) 
     { 
      p[i] = new Posting(); 
      p[i].title = "this is " + i ; 
     } 

     return p ; 
    } 
1

需要初始化数组中的每个对象。

p[i] = new Posting(); 
p[i].title = "this is " + i ; in the for loop. 
0

之前添加以下行这样做:Posting[] p = new Posting[100];

将创造100个空对象的数组。 P [0],P [1],P [2] ..... P [99] = NULL 所以当你:

p[i].title 

它实际上等同于:null.title ,因此你得到的NullPointerException 。