0

Can anyone tells me why there is a NullPointerException in the following code? I tried to figure it out but couldn't!

The exception is in the following line :

companies[x].compName=temp1[0];

The companies array type is Company that contains a String and an Array List.

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 
Han
  • 3,052
  • 2
  • 22
  • 31
  • 1
    Didn't read your code. But from the first line, there are three (inclusive OR) possibilities: (1) companies is null. (2) companies[x] is null. (3) temp1 is null. So go through and make sure none of those three things can happen, or that you handle it appropriately, if and when it does. – Jameson Nov 08 '15 at 10:39
  • Ok I will try to check it again. – Metanoia Nov 08 '15 at 10:47

1 Answers1

1

See my comment - company[x] was never initialied to be a Company(). It's not enough to initialize the array - every item in it needs to be assigned as well.

You might be better of using a List as the number of lines you use to initialize the array might not be the number of companies at all (some lines are skipped)

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++){
Jan
  • 13,738
  • 3
  • 30
  • 55