java - 空指针异常

标签 java nullpointerexception

谁能告诉我为什么下面的代码中出现 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/

相关文章:

java - android 上的空指针异常

java - 如何检查数组是否为空或数组内容是否为空

java - 使用 Jackson 反序列化为自定义对象的 HashMap

java - CustomAdapter 不显示列表中的 arraylist 项目

java - Android:是什么让我的应用程序崩溃?

java - Swing 中线程 "AWT-EventQueue-0"NullPointerException 错误

java - 什么是NullPointerException,我该如何解决?

java - 如何加载与当前类不在同一个 jar 存档中的类?

java - 如何使用 Java 7 的新文件 API 检查路径是否指向现有文件?

Java,更新 map