NullPointerException与扫描仪 [英] NullPointerException with Scanner
本文介绍了NullPointerException与扫描仪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在第5行收到NullPointerException.我不太确定为什么或如何解决它...
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;
}
有指针吗?
推荐答案
尽管通常使用equals
方法比较Java对象,但null
比较是一个明显的例外:没有Java Object
将equal
与null
-Java类需要满足此要求:
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:
对于任何非空参考值x,
x.equals(null)
应该返回false
.
此外,file
是以null
开头的,因此调用其中的任何方法(包括equals
)都将导致NPE.
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) {
...
}
这篇关于NullPointerException与扫描仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文