slick_57
slick_57

Reputation: 31

Array Value Passing from a Scanner Object instance

I am working on a chunk of code that is supposed to read input from a file and compare it against user inputs in order to check if the user input is within the file. I have gotten the scanner object to print to the console, but whenever I try to save it to an array value I get a null pointer exception and cannot seem to figure out why. Any help is greatly appreciated.

public void cpySearch() throws FileNotFoundException {
    Integer y = 0;
    String FIPSrg = "[\\d]+,[A-Z]";
    String CountyRg = "[a-z A-Z]+\\s+[a-z A-Z]+";
    Integer yrIndex = Integer.parseInt(String.valueOf(year.toString().charAt(3)));
    System.out.println("Year Index: " + yrIndex);
    FileReader popInfo = new FileReader("/home/(myUser)/Documents/Code - OCT 15/Java/County_Population/src/populationInfo.txt"); //These lines (in each method) may need to be
    // replaced pending the machine its run on
    Scanner pop_info_scanner = new Scanner(popInfo);                    //Create Scanner instance to parse lines

    while (pop_info_scanner.hasNextLine()){
        //Finds the FIPS code
        //System.out.println("popinfoscn: " + pop_info_scanner);



        //Suppposed to find the substring of FIPS


        System.out.println(pop_info_scanner.nextLine().substring(0,5)); //This prints correct
        FIPScode[y] = pop_info_scanner.nextLine().substring(0,5);//This is the null error


        System.out.println("Found Fips: " + FIPScode[y]);

        if (FIPScode[y].equals(FIPS.toString())){
            System.out.println("We Made it to FIPS");
        }
        // else if (pop_info_scanner.nextLine().contains(CountyRg)){
        //    County[y] = pop_info_scanner.toString();
        // }
        y++;
    }
}

Upvotes: 1

Views: 40

Answers (1)

Aharon K
Aharon K

Reputation: 324

First of all, many people will comment on your use of snake_case, as in Java normally camelCase is used for variables.

As to your question, your loop calls a NullPointerException because instead of

  • Reading each line
  • Printing it
  • Storing it to FIPScode[y]

You are instead

  • Checking if there is another line
  • Printing it
  • Storing the next line to FIPScode[y], because of the second .nextLine() call.

So when you get to the last line, you see there's another, you print it, and then try to get the next line, which is null and throws an error.

It may work better to write

String nextLine;
while (pop_info_scanner.hasNextLine()){

    nextLine = pop_info_scanner.nextLine();

    System.out.println(nextLine.substring(0,5));
    FIPScode[y] = nextLine.substring(0,5);

    //...

Or even to make the variable nextLineSubstring = pop_info_scanner.nextLine().substring(0,5) if you always only want the substring.

As another aside, your last y call, perhaps in FIPScode[y].equals(FIPS.toString()), can be y++, and you do not need the increment as its own line.

Upvotes: 2

Related Questions