当我需要通过方法 close()
关闭 Scanner
时,我的代码如下,任何人都可以解释为什么我需要检查 if (输入!= null
)好吗?
Scanner input = new Scanner(new File("System.txt"));
...
Public void closeFile() {
if(input != null) {
input.close();
}
}
最佳答案
could any one explain why I need to check if(input != null) please ?
它只是一个空检查
,如果输入为空,它会抛出NullPointerException。
考虑下面的代码:
Scanner input = new Scanner(new File("System.txt"));
public void someMethod(){
input = doSomething(); //say doSomething() returns null
}
Public void closeFile()
{
if(input != null)
input.close();
}
现在,由于输入为空,如果您尝试调用 close() ,它会抛出 NPE>
关于java - 解释 Scanner close( ) 方法 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14356715/