Shikha
Shikha

Reputation: 49

Null Pointer Exception In Java while reading a file

I am trying to read a file using scanner in Java. I get the following output and error when I run the below piece of code.

Exception in thread "main" java.lang.NullPointerException at PageRank$ReadInput.ReadFile(PageRank.java:29) at PageRank.main(PageRank.java:58)

Please help me fix this error.

public class PageRank{
public static class ReadInput{
    private Scanner x;
    public void OpenFile(){
        try {
            File file  = new File("input.txt");
            Scanner x=new Scanner(file);
       }
        catch(Exception e){
            System.out.println("File does not exist.");
        }


    }
    public void ReadFile() {
        while (x.hasNextLine() ) {
            String s = x.nextLine();
            System.out.println(s);
            String s1 = x.nextLine();
            String s2 = x.nextLine();
            System.out.println(s);
            System.out.println(s1);
            System.out.println(s2);
        }
    }

    }
public static void main(String[] args)throws Exception
    {
    ReadInput P = new ReadInput();
    P.OpenFile();
    P.ReadFile();
      }

}

Upvotes: 0

Views: 928

Answers (1)

user9849588
user9849588

Reputation: 607

In OpenFile(), inside the try block, you have to remove the 'Scanner' in

Scanner x=new Scanner(file);

and leave it as

x=new Scanner(file);

Explanation:

In your code, when you write

Scanner x=new Scanner(file);

inside the try block, you are creating a new variable but with the same name as the one you declared at the beginning of the class at

private Scanner x;

Now you would have two Scanner variables named 'x'. Inside the try statement, you are initializing the one inside that block, but it only exists there, so as soon you leave the try block it gets destroyed.

Now back to the ReadFile() function, you are calling x.hasNextLine(), but this 'x' is the one you declared at the beginning, not the one inside the try statement, so it is still uninitialized.

Upvotes: 1

Related Questions