Java NullPointerException occurs when using scanner.hasNext();
I came up with the following code to read the information from the file:
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();
}
}
However, I get a NullPointer error in the (while(s.hasNext())) line and can’t find a solution.
I’m working in Eclipse and the file I’m reading is properly imported into the project, so this shouldn’t be a problem.
Edit:
How I access the method:
public class Tester {
public static void main(String[] args) {
Reader read = new Reader();
read.openFile();
read.readFile();
read.closeFile();
}
}
Solution
According to the statement thrown by NPE, while (s.hasNext()),
s is most likely a null pointer, you can add System.out.println(s);
Double confirm the statement before it.
As for the reason why s
is null
, there are two possible causes:
- You did not call
openFile
beforereadFile
- An exception is thrown when opening a file.
s
is just a declaration and does not yet point to any object.
Perhaps for better practice, you can assert whether an instance is null
or not before calling its methods. From what I understand, readFile
depends on the result of openFile
, maybe you can set the return value of openFile
to a boolean value and check the return value before further open file operations. Files that can’t be read or even opened, right?
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();
}
}
The caller can do the following:
Reader reader = new Reader();
if (reader.openFile())
reader.readFile();