谁能告诉我为什么下面的代码中出现 NullPointerException ?我试图弄清楚,但没有成功!
异常(exception)情况在以下行:
companies[x].compName=temp1[0];
公司数组类型是 Company,包含一个字符串和一个数组列表。
JFileChooser fileChooser = new JFileChooser(); // create instence from file chooser
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); //assign directory
if(fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION){
File f = fileChooser.getSelectedFile();
try{
LineNumberReader lnr = new LineNumberReader(new FileReader(f));
lnr.skip(Long.MAX_VALUE);
int n = lnr.getLineNumber() +1;
lnr.close();
companies = new Company[n];
int i=0 , x=0;
String s ="";
Scanner input = new Scanner(f);
String [] temp1,temp2;
while(input.hasNext()){ // read line by line
s = input.nextLine();
s=s.replaceAll(" ", "");
if(s == null)
continue;
else{
temp1 =s.split(",");
companies[x].compName=temp1[0]; //store compName in the companies
for( i=1;i<temp1.length;i++){
temp2=temp1[i].split("/");
companies[n].compItems.addLast(temp2[0], Integer.parseInt(temp2[1]));
} //end for
} //end else
x++;
} //end while
最佳答案
请参阅我的评论 - company[x] 从未初始化为 Company()。初始化数组是不够的 - 还需要分配其中的每个项目。
您可能最好使用列表,因为用于初始化数组的行数可能根本不是公司的数量(某些行被跳过)
while(input.hasNext()){ // read line by line
s = input.nextLine();
s=s.replaceAll(" ", "");
if(s == null)
continue;
else{
temp1 =s.split(",");
//companies[x] is still null - initialize this!
companies[x] = new Company();
//Now this should be fine
companies[x].compName=temp1[0]; //store compName in the companies
for( i=1;i<temp1.length;i++){
关于java - 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33593016/