首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >空指针异常

空指针异常
EN

Stack Overflow用户
提问于 2015-11-08 10:36:09
回答 1查看 63关注 0票数 0

有人能告诉我为什么在下面的代码中有一个NullPointerException吗?我试过想办法,但没办法!

例外情况出现在以下一行:

代码语言:javascript
复制
companies[x].compName=temp1[0];

companies数组类型是Company,它包含字符串和数组列表。

代码语言:javascript
复制
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 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-08 10:53:05

参见我的评论-公司从来没有被初始化为一个公司()。仅仅初始化数组是不够的--数组中的每一项都需要分配。

您最好使用列表,因为用于初始化数组的行数可能根本不是公司的数量(有些行被跳过了)。

代码语言:javascript
复制
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++){
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33593016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档