I've created this code in Java which opens a file if it exists in my pc and read from it the number of words. When trying to execute NUllPointerException
occurs in the line "x.hasNext() "
eventhough I've created an object of x.
Can someone explain this? Notice that the file already exists in my pc
import java.io.*;
import java.util.*;
public class nrFjaleve {
private Scanner x;
public void open(){
try{
x=new Scanner(new File("p.txt"));
}
catch(Exception e){
System.out.println("The file doesnt exist");
}
}
public void read()
{
while(x.hasNext()){
int nr=0;
String a = x.next();
nr++;
}
}
public void close() {
x.close();
}
public static void main(String[] args)
{
nrFjaleve ob=new nrFjaleve();
//ob.exist();
ob.read();
ob.open();
ob.close();
}
}