0

Why is there a null exception pointer error being thrown and how can i fix this thank you. If you could explain what to do. I am trying to store each line from a txt file into an arraylist which goes into a larger array list of seperate lines.

    public static ArrayList<ArrayList<String>> addAfter(String file1)throws IOException{
    Scanner scanner = new Scanner(new File(file1));
    ArrayList<ArrayList<String>> arr = new ArrayList<ArrayList<String>>(); 
    ArrayList<String> a = null;
    boolean check = false;
    while(scanner.hasNextLine())
    {
        String str = scanner.nextLine();
        String[] stringArr = str.split(" +");
        for(int i=0; i<stringArr.length; i++){
            a.add(stringArr[i]); //null exception being thrown here
        }
        stringArr = null;
        arr.add(a);
        a.clear();
    }
    return arr;
    }
Maciej Jureczko
  • 1,560
  • 6
  • 19
  • 23
Blueynuey
  • 23
  • 2

3 Answers3

1

because of this:

ArrayList<String> a = null;

ArrayList was declared but wasn't initialized. So when you access the ArrayList inside the for loop, you are basically accessing variable a which refers to null.

instead, do:

ArrayList<String> a = new ArrayList<String>();

Also, you have another problem in your code: You wish to create an ArrayList of ArrayList where you are passing the same object's reference in the loop (not creating new ArrayList in the loop) and clearing it in the end of for loop. This causes the same ArrayList being added to all the indexes of the ArrayList<ArrayList<>>. You'll have to do a new ArrayList<String>() for every new row you wish to insert in the arrayList.

Modifying your code to do the same:

public static ArrayList<ArrayList<String>> addAfter(String file1)throws IOException{
Scanner scanner = new Scanner(new File(file1));
ArrayList<ArrayList<String>> arr = new ArrayList<ArrayList<String>>(); 
ArrayList<String> a = null;
boolean check = false;
while(scanner.hasNextLine())
{
    a = new ArrayList<String>(); // add this
    String str = scanner.nextLine();
    String[] stringArr = str.split(" +");
    for(int i=0; i<stringArr.length; i++){
        a.add(stringArr[i]); //null exception being thrown here
    }
    stringArr = null;
    arr.add(a);
    //a.clear(); -- remove this line
}
return arr;

In Java, you pass references and not values (for objects).

Parijat Purohit
  • 921
  • 6
  • 16
1

You did not initialize the "a" ArrayList object.

ArrayList<String> a = new ArrayList<>();

instead of

ArrayList<String> a = null;

In Java, object variables do not contain the object itself, but a reference to where the object is really located in memory. When you get a NullPointerException, it means that Java cannot access an object because the object variable is null instead of a reference to an object.

ismaro3
  • 79
  • 1
  • 5
1

Use this.

ArrayList<String> a = new ArrayList<>();
Sumit Shitole
  • 110
  • 1
  • 3
  • 20