NullPointerException with Scanner

不羁岁月 提交于 2019-12-13 05:56:08

问题


I am getting a NullPointerException on the 5th line. I am not really sure why or how to fix it...

    public static Scanner getInputScanner(Scanner console){
    Scanner inputFile = new Scanner(System.in);
    Scanner file = null;
    String userInputFile = null;
    while (file.equals(null)) {
        try {
            System.out.print("Enter input file: ");
            userInputFile = inputFile.nextLine();
            file = new Scanner(new File(userInputFile));
        } catch (FileNotFoundException e) {
            System.out.print(userInputFile + " (No such file or directory)");
            file = null;
            return file;
        }
    }
    return file;
}

Any pointers?


回答1:


Although you generally compare Java objects using the equals method, null comparison is a notable exception: no Java Object compares equal to null - Java classes need to satisfy this requirement:

For any non-null reference value x, x.equals(null) should return false.

Moreover, file is null to start with, so calling any methods on it, including equals, will result in NPE.

Therefore, you need to use reference equality instead:

while (file == null) {
    ...
}



回答2:


In the fifth line, you have while (file.equals(null)), which attempts to call the equals method on file. However, you explicitly set that variable to null on the third line: Scanner file = null;, which will of course result in the NullPointerException you received when any method on it is used.

If you want to check whether the variable is null, you must not attempt to call any method on it - use while (file != null) instead. (With your current code, nothing in the while will ever execute because you never initialized file.)




回答3:


In line 5 you are using variable file which is set to null in line 3. You need to set a variable to a non null value before you can call methods on it.



来源:https://stackoverflow.com/questions/31326638/nullpointerexception-with-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!