This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12个答案)
4年前关闭。
谁能告诉我下面的代码为什么会有NullPointerException?我试图弄清楚,但不能!
以下行是例外:
companies数组类型为Company,其中包含字符串和数组列表。
(12个答案)
4年前关闭。
谁能告诉我下面的代码为什么会有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
最佳答案
请参阅我的评论-company [x]从未被初始化为Company()。初始化数组是不够的-数组中的每个项目也都需要分配。
您最好使用List,因为用于初始化数组的行数可能根本不是公司数(跳过了一些行)
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++){