当我运行这段代码时,
/*
* 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)
你有什么想法吗?
最佳答案
您必须在设置字段之前初始化数组元素。
p[i] = new Posting(/* ... */);
// THEN set the fields
p[i].title = /* ... */;
关于java - 在 Java 中返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7239197/