问题
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 returnfalse
.
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