I'm fairly new to programming and I wanted to learn how to read data from a file. I watched this video and tried to copy the idea for my own purpose. https://www.youtube.com/watch?v=3RNYUKxAgmw
Whenever I try to run my main it says Error Line 22 - NullPointerException. I have a text file with numbers and I have checked if the names match. I simply do not understand why it says my file is empty.
package uge4;
import java.util.*;
import java.io.*;
public class ReadFile {
private Scanner x;
public void openFile () {
try {
x = new Scanner (new File("gradeconverter.txt"));
} catch(FileNotFoundException e){
System.out.println("File not found.");
}
}
public void readFile() {
Scanner input = new Scanner(System.in);
System.out.print("Insert old grade ");
int grade = input.nextInt();
input.close();
// line 22
while(x.hasNextInt()) {
int a = x.nextInt();
int b = x.nextInt();
if ( a == grade) {
System.out.println("Your new grade is: "+b);
}
}
}
public void closeFile() {
x.close();
}
}
xvariable is null. Was there a "File not found." prompt in the console when you ran it? Had you actually calledopenFile()before you calledreadFile()?openFilebeforereadFile?