I am having trouble reading from a text file and i keep getting the error "java null pointer exception"
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? 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*; class and the java.util class as well. Error occurs at 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()
). Checking is always a good idead. But then you should read only the next element (via next()
) and not further without checking again.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.