[英]Java Null Pointer Exception when reading from text file
I am having trouble reading from a text file and i keep getting the error "java null pointer exception" 我无法从文本文件中读取内容,并且不断收到错误“ java空指针异常”
My read file class is 我的读取文件类是
public class readfile {
private Scanner x;
public void openfile() {
try {
x = new Scanner(new File("test2.txt"));
}
catch(Exception e) {
System.out.println("error");
}
}
public void readfile() {
while(x.hasNext()) {
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s",a,b,c);
}
}
and my main class to call these methods is 我的主要方法是调用这些方法
public class InputOut {
public static void main(String[] args) {
readfile r = new readfile();
r.openfile();
r.readfile();
r.closeFile();
}
}
i get the error when i call the readfile exception so i believe i might not be opening it correctly? 调用readfile异常时出现错误,所以我相信我可能无法正确打开它? I saved the file in the directory where the program is run and has the follwoing format
我将文件保存在程序运行的目录中,并且具有以下格式
50 issac billy
432 bryan darren
443 rob zombie
did i miss something to read files here. 我错过了一些在这里读取文件的东西吗? I imported the java.io*;
我导入了java.io *; class and the java.util class as well.
类和java.util类。 Error occurs at
public void readfile()
在
public void readfile()
处发生错误
Just a quick guess... Your code is 快猜一下...您的代码是
while(x.hasNext()) {
String a = x.next();
String b = x.next();
String c = x.next();
hence you are checking if ONE element exists (via hasNext()
). 因此,您正在检查ONE元素是否存在(通过
hasNext()
)。 Checking is always a good idead. 检查始终是一个好主意。 But then you should read only the next element (via
next()
) and not further without checking again. 但是然后您应该只读取下一个元素(通过
next()
),而不要进一步检查而无需进一步检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.