有人能告诉我为什么在下面的代码中有一个NullPointerException吗?我试过想办法,但没办法!
例外情况出现在以下一行:
companies[x].compName=temp1[0];companies数组类型是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 发布于 2015-11-08 10:53:05
参见我的评论-公司从来没有被初始化为一个公司()。仅仅初始化数组是不够的--数组中的每一项都需要分配。
您最好使用列表,因为用于初始化数组的行数可能根本不是公司的数量(有些行被跳过了)。
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++){https://stackoverflow.com/questions/33593016
复制相似问题