我正在尝试填充用户定义类型的数组 - 3个字符串的复合和1个布尔值。类型名称为PrinterType.
,其中包括SET和GET这三个字符串和布尔值的方法。
我正在尝试在另一个将要执行数组填充的类文件中使用它但是当我运行该项目时,我得到java.lang.NullPointerException
。
我知道这是字符串字段未初始化的问题,但我不知道如何初始化用户定义类型数组的字符串字段。我希望有人可以帮助我。用户定义的类型和实现类如下所示。
顺便说一句,错误指向实现类的行:Printers[i].setPersonality(aLineOfText[0].toString());
//implementing class =======================================
package MainPkg;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadDefinitions
{
final String sFileName = "C:/Definitions OEvP/Printers.txt";
private static int iNoOfLines;
public PrinterType[] Printers;
private int getNumberOfLines() throws IOException
{
FileReader fr = new FileReader(sFileName);
BufferedReader br = new BufferedReader(fr);
iNoOfLines = 0;
while (br.readLine() != null)
{
iNoOfLines++;
}
br.close();
fr.close();
return iNoOfLines;
}
public void setArray() throws IOException
{
Printers = new PrinterType[this.getNumberOfLines()];
int i = 0;
FileReader fr = new FileReader(sFileName);
BufferedReader br = new BufferedReader(fr);
String[] aLineOfText = {};
while (i != this.getNumberOfLines())
{
aLineOfText = br.readLine().split(";");
Printers[i].setPersonality(aLineOfText[0].toString());
Printers[i].setProductNumber(aLineOfText[1].toString());
Printers[i].setPL(aLineOfText[2].toString());
if ("1" == aLineOfText[3].toString())
{
Printers[i].setHipot(Boolean.TRUE);
}
else
{
Printers[i].setHipot(Boolean.FALSE);
}
i++;
aLineOfText = null;
System.gc();
}
}
}
//user defined Class ======================================
package MainPkg;
public class PrinterType
{
private String sPersonality;
private String sProductNumber;
private String sPL;
private Boolean bHipot;
//constructor
PrinterType()
{
sPersonality = "test";
sProductNumber = "test";
sPL = "test";
}
//printer information
//set methods
public void setPersonality(String localString)
{
sPersonality = localString;
}
public void setProductNumber(String localString)
{
sProductNumber = localString;
}
public void setPL(String localString)
{
sPL = localString;
}
public void setHipot(Boolean localBoolean)
{
bHipot = localBoolean;
}
//get methods
public String getPersonality()
{
return sPersonality;
}
public String getProductNumber()
{
return sProductNumber;
}
public String getPL()
{
return sPL;
}
public Boolean getHipot()
{
return bHipot;
}
}
答案 0 :(得分:1)
您没有初始化打印机阵列的项目。
您只是创建一个PrinterType的空项目数组。
Printers = new PrinterType[this.getNumberOfLines()];
// Initialization
for(int i = 0, l = this.getNumberOfLines(); i < l; i++)
Printers[i] = new PrinterType();