Java NullPointerException when using scanner.hasNext();

flowz0r :

I came up with the following code to read information from a 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 on the (while (s.hasNext())) line and can't find a solution.

I'm working in Eclipse and the file I'm reading from is imported correctly into the project so that should not be an issue.

EDIT:

The way I access the methods:

public class Tester {

    public static void main(String[] args) {

        Reader read = new Reader();

        read.openFile();
        read.readFile();
        read.closeFile();

    }

}
Eugene :

As per the statement where NPE throws, while (s.hasNext()), it's most probable that the s is null pointer, you can add System.out.println(s); before that statement to double confirm it.

And for the reason why the s is null, there are two possible reasons:

  1. You didn't invoke openFile before readFile
  2. Exception is thrown when you open the file. The s is only a declaration and hasn't pointed to any object yet.

Maybe for a better practice, you can assert whether a instance is null or not before invoking its method. And as per my understanding, the readFile depends on the result of openFile, maybe you can set return value of openFile like a boolean value and check the return value before further open file operation. It's impossible to read a file which can't be even open, 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 invoker can do something like below:

Reader reader = new Reader();
if (reader.openFile())
    reader.readFile();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=4320&siteId=1