Java 从扫描仪对象实例传递的数组值

Java 从扫描仪对象实例传递的数组值,java,arrays,loops,file,java.util.scanner,Java,Arrays,Loops,File,Java.util.scanner,我正在处理一段代码,该代码应该从文件中读取输入,并将其与用户输入进行比较,以检查用户输入是否在文件中。我已将scanner对象打印到控制台,但每当我尝试将其保存为数组值时,就会出现空指针异常,似乎无法找出原因。非常感谢您的帮助 public void cpySearch() throws FileNotFoundException { Integer y = 0; String FIPSrg = "[\\d]+,[A-Z]"; String Count

我正在处理一段代码,该代码应该从文件中读取输入,并将其与用户输入进行比较,以检查用户输入是否在文件中。我已将scanner对象打印到控制台,但每当我尝试将其保存为数组值时,就会出现空指针异常,似乎无法找出原因。非常感谢您的帮助

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++;
    }
}

首先,许多人会评论您对
snake\u case
的使用,因为在Java中,
camelCase
通常用于变量

至于你的问题,你的循环调用了一个
NullPointerException
,因为

  • 读每行
  • 打印它
  • 将其存储到
    FIPScode[y]
相反,你是

  • 检查是否有其他线路
  • 打印它
  • 由于第二个
    .nextLine()
    调用,正在将下一行存储到
    FIPScode[y]
所以当你到达最后一行时,你会看到还有另一行,你打印它,然后尝试得到下一行,它是空的,并抛出一个错误

写作可能更有效

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);

    //...
或者,如果始终只需要子字符串,甚至可以使变量
nextLineSubstring=pop\u info\u scanner.nextLine().substring(0,5)

另一方面,您最后的
y
调用,可能在
FIPScode[y].equals(FIPS.toString())
中,可以是
y++
,您不需要将增量作为自己的行