0

I have the following code below. If I comment out the stringList.add(row); I can get it to print the lines of the document (5 lines of text with spaces). If I don't comment it out, I get one line printed and the null. I have looked up everything I could online but I am not understanding why this is happening!

package examples.files;

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * @author 
 *
 */
public class ReadFileUsingScanner {
    static ArrayList<String> stringList = null;
    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) {
        Scanner scanner = null;

        try {
            scanner = new Scanner(new File("customers.txt"));

            while (scanner.hasNext()) {
                String row = scanner.nextLine();
                System.out.println(row);
                stringList.add(row);
            }
        } catch(Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (scanner != null) {
                try {
                    scanner.close();
                } catch (Exception e) {}
            }
        }
    }

}

You don't have to solve the code but I want to understand the fundamentals as to why it doesn't work.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

4

Your arrayList is not initialized. Change to

static ArrayList<String> stringList = new ArrayList<String>();
Md Johirul Islam
  • 5,042
  • 4
  • 23
  • 56
0

The bug is NPE(NullPointException).

And the next time you get a bug,you may not need to ask a question on StackOverFlow.Try Debugger Function of the IDE line by line.You will get the answer.

Dai Kaixian
  • 1,045
  • 2
  • 14
  • 24