我想填充用戶定義類型的數組--3個字符串和1個布爾值的組合。類型名稱爲PrinterType.
,其中包含用於這3個字符串和布爾值的SET和GET的方法。Java用戶定義類型的數組
我想在另一個類文件中使用它,其中數組人口將被執行,但是當我運行該項目時,我得到了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;
}
}
爲什麼使用「打印機[i] .setPersonality(aLineOfText [0] .toString());」而不僅僅是「Printers [i] .setPersonality(aLineOfText [0]);」因爲當我看到你的代碼是字符串類型的,所以沒有必要在它上面調用toString()? – RE350 2014-11-09 09:09:04
嗨生氣,謝謝,我忽略了那一個。非常喜歡使用toString()。但我已經修改了代碼並仍然有相同的錯誤。它可能是它不可能在Java? – jude 2014-11-09 10:28:05
訣竅是*讀*錯誤堆棧跟蹤,知道錯誤來自哪裏。沒有這個堆棧跟蹤,我們不得不猜測,而不是知道。 – 2014-11-09 11:53:17