1
private ArrayList<Record> readFromFile(String fileName) {
    int lineNumber = 0;
    Scanner fileReader;
    ArrayList<Record> recs = new ArrayList<>();
    try {
        fileReader = new Scanner(new File(fileName));
        while(fileReader.hasNextLine()) {
            lineNumber++;
            String line = fileReader.nextLine();
            String stateCode = line.substring(0,2).trim();
            String distCode = line.substring(3,8).trim();
            String distName = line.substring(9,81).trim();
            int population = Integer.parseInt(line.substring(82,90).trim());
            int childPopulation = Integer.parseInt(line.substring(91,99).trim());
            int childPovertyPopulation = Integer.parseInt(line.substring(100,108).trim());
            String miscStats = line.substring(109).trim();
            String[] data = new String[6];
            data[0] = stateCode;
            data[1] = distCode;
            data[2] = distName;
            data[3] = String.valueOf(population);
            data[4] = String.valueOf(childPopulation);
            data[5] = String.valueOf(childPovertyPopulation);
            data[6] = miscStats;
            recs.add(new Record(stateCode, distCode, distName, population, childPopulation, childPovertyPopulation, miscStats));
        }
        fileReader.close();
    } catch(FileNotFoundException fnfe) {
        System.out.println("Cannot locate file: " + fileName);
        System.exit(0);
    }
    return recs;
}

the error occurs at the end of the method when I try to return "recs" with a NullPointerException thrown. Why is this happening?

Dark
  • 11
  • 2
  • 1
    I think you are mistaken. It is not possible for `return recs;` to throw an NPE. Show us the stacktrace for the NPE. – Stephen C Aug 23 '20 at 23:59
  • 1
    Also, please fix up the indentation for your code. ("Still learning" is not a reason to inflict messy stuff on the people who you want to help you.) – Stephen C Aug 24 '20 at 00:02
  • I don’t see any obvious causes of a NullPointerException, but I know `data[6] = miscStats;` will cause an ArrayIndexOutOfBoundsException. (What is the length of `data`? How many elements are you actually trying to place in `data`?) – VGR Aug 24 '20 at 02:04
  • Why even have the data array? Just put the elements directly into the record. – NomadMaker Aug 24 '20 at 05:36

1 Answers1

-1

It's little hard to tell from the code, but I think the fileReader.hasNextLine() is returning false and its not running the while loop.

Put a println inside the while loop. If you put something like this System.out.println("Found next lines");

If you don't see this in the output, then you know that it is not running the loop.

Your code is finding the file since it is not returning FileNotFoundException, but it not returning false when checking for the next line.

James Pak
  • 1
  • 1