java - 使用scanner.hasNext()时出现Java NullPointerException;
问题描述
我想出了以下代码来从文件中读取信息:
import java.io.*;
import java.util.*;
public class Reader {
private Scanner s;
public void openFile() {
try {
s = new Scanner(new File("file.txt"));
} catch (Exception e) {
System.out.println("File not found. Try again.");
}
}
public void readFile() {
while (s.hasNext()) {
String a = s.next();
String b = s.next();
String c = s.next();
int d = s.nextInt();
int e = s.nextInt();
int f = s.nextInt();
}
public void closeFile() {
s.close();
}
}
但是,我在 ( while (s.hasNext()) ) 行上收到 NullPointer 错误并且找不到解决方案。
我在 Eclipse 中工作,并且我正在读取的文件已正确导入到项目中,因此这应该不是问题。
编辑:
我访问方法的方式:
public class Tester {
public static void main(String[] args) {
Reader read = new Reader();
read.openFile();
read.readFile();
read.closeFile();
}
}
解决方案
根据 NPE 抛出的语句,while (s.hasNext())
很可能s
是空指针,您可以System.out.println(s);
在该语句之前添加以双重确认。
而对于s
is的原因null
,有两个可能的原因:
openFile
你之前没有调用readFile
- 打开文件时抛出异常。这
s
只是一个声明,还没有指向任何对象。
null
也许为了更好的实践,您可以在调用其方法之前断言实例是否存在。根据我的理解,这readFile
取决于 的结果openFile
,也许您可以将返回值设置openFile
为布尔值,并在进一步打开文件操作之前检查返回值。无法读取甚至无法打开的文件,对吧?
import java.io.*;
import java.util.*;
public class Reader {
private Scanner s;
public boolean openFile() {
try {
s = new Scanner(new File("file.txt"));
return true;
} catch (Exception e) {
System.out.println("File not found. Try again.");
return false;
}
}
public void readFile() {
while (s.hasNext()) {
String a = s.next();
String b = s.next();
String c = s.next();
int d = s.nextInt();
int e = s.nextInt();
int f = s.nextInt();
}
}
调用者可以执行如下操作:
Reader reader = new Reader();
if (reader.openFile())
reader.readFile();
推荐阅读
- reactjs - 如何让 React 输入文本并选择?
- matrix - 倾斜/倾斜纹理 - Monogame
- c# - C#,“复合组件”/用户控件
- python - 搜索两个数据框以了解变量何时在同一行相遇
- docker - 同一个 Docker 层怎么会有不同的大小?
- excel - 从 Windows 服务应用程序运行 Excel 宏时出错
- kubernetes-helm - Helm模板 - 如何在数组中使用“如果至少存在一个”?
- python - Python重新查找所有匹配的重复模式
- ruby - 用于 Sed 命令的 Ruby Escape 反斜杠
- javascript - Ajax/jQuery 脚本如何在一个表单 url 中显示 2+ 个相关的下拉框条目?