【问题标题】:Attempt to invoke virtual method on a null object reference issue [duplicate]尝试在空对象引用问题上调用虚拟方法 [重复]
【发布时间】:2016-12-31 10:34:13
【问题描述】:

我正在开发一个使用以下代码的应用程序。它正在生成一个意外错误,如“尝试在空对象引用上调用虚拟方法”。我不明白为什么会这样。错误作为包含t[i].setTestname(getData(exams[i])); 的行被抛出。有人可以指出我做错了什么。可以在这里使用一些帮助。

void processTestPerformance()
{
    String exams[],rawdata;
    rawdata=data.toString();
    int numberoftests=getNumbers("tabletitle03",rawdata);
    Tests[] t= new Tests[numberoftests];
    exams=new String[numberoftests];
    rawdata=rawdata+"tabletitle03";
    for(int i=0;i<numberoftests;i++)
    {
        int j=rawdata.indexOf("tabletitle03");
        int k=(rawdata.substring(j+1)).indexOf("tabletitle03");
        exams[i]=rawdata.substring(j,j+1+k);
        t[i].setTestname(getData(exams[i]));
        rawdata=rawdata.substring(k);
    }
}

Tests类的代码如下:

public class Tests
{
    public int numberofsubjects;
    public String testname;
    public Subject s[];
    public void setS(Subject[] s)
    {
        this.s = s;
    }
    public void setNumberofsubjects(int numberofsubjects)
    {
        this.numberofsubjects = numberofsubjects;
        s=new Subject[numberofsubjects];
    }
    public void setTestname(String testname)
    {
        this.testname = testname;
    }
}

提前致谢。

【问题讨论】:

    标签: java android class


    【解决方案1】:

    您创建一个空数组 Tests 类,大小为 numberoftests

    如果您查看该数组内部,您会发现一个空序列。因为你从不初始化它。

    您只需要填充数组,以便t[i] 将返回您的类的实例。

    在你的 for 循环中,你可以例如使用默认构造函数:

    t[i] = new Tests();
    // now you can manipulate the object inside the array
    t[i].etTestname(getData(exams[i]));
    

    【讨论】:

      【解决方案2】:
      for(int i=0;i<numberoftests;i++)
              t[i]=new Tests();
      

      这解决了我的问题。

      【讨论】:

        猜你喜欢
        • 2023-03-25
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2016-07-30
        • 2015-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多