2016-12-31 128 views
2

我正在开发使用以下代码的应用程序。它正在产生一个意外的错误,如“尝试在空对象引用上调用虚拟方法”。我不明白为什么会发生这种情况。该错误是由包含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); 
    } 
} 

代码类的测试如下:在提前

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; 
    } 
} 

感谢。

回答

1

创建Tests类的空数组,大小numberoftests

的如果你看看这个数组,你会发现空的序列中。因为你永远不会初始化它。

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

在您的周期可以例如使用默认的构造函数:

t[i] = new Tests(); 
// now you can manipulate the object inside the array 
t[i].etTestname(getData(exams[i])); 
0
for(int i=0;i<numberoftests;i++) 
     t[i]=new Tests(); 

这解决了我的问题。

相关问题