Reputation: 11
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();
}
}
Upvotes: 0
Views: 201
Reputation: 2370
Can u simply use the java 8 "way"
Files.lines(Paths.get(FILE_PATH)).forEach(System.out::print);
PS: You have forget to open the Scanner
-> x
Upvotes: 0
Reputation: 121
After first int a = x.nextInt()
calls another int b = x.nextInt();
, it may happend that x
Scanner has no more data to return. You need to check x.hasNextInt()
before each call of x.nextInt()
method.
Upvotes: 2
Reputation: 3971
i guess it is because you havnt specified the path of your file
if you are uding a file from your pc/latop's harddisk please give the complete path
x = new Scanner (new File("C://newfolder//gradeconverter.txt"));// just an example, add the actual path of you files location
Upvotes: 0