Reputation: 103
I'm fairly new to Java and I'm having a difficult time understanding the scanner and exceptions. It's showing a NullPointerException at "while (! line.matches("[\n\r]+"))". I'm not really sure why this is happening. I've initialized the line variable and I'm assuming that if the next line of the scanner is a break line, the while loop should end. If the next line is null then the entire outer loop should end. Why is this returning a NullPointerException?
public class Readfile {
private static int inputs = 0;
public void main(String filename) throws Exception {
URL url = getClass().getResource(filename);
File file = new File(url.getPath());
parsefile(file);
}
void parsefile(File file) throws Exception {
ArrayList<String[]> Inputs = new ArrayList<String[]>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while (line != null){
LinkedList currentinput = new LinkedList();
if (line.contains("Input")){
while (! line.matches("[\\n\\r]+")) {
System.out.println(line);
line = br.readLine();
}
}else{
line = br.readLine();
}
}
}
}
Upvotes: 1
Views: 54
Reputation: 201447
Your inner loop also calls br.readLine()
, so you need to check for null
. Change
while (! line.matches("[\\n\\r]+")) {
to something like
while (line != null && ! line.matches("[\\n\\r]+")) {
or
while (! line.matches("[\\n\\r]+")) {
System.out.println(line);
line = br.readLine();
if (line == null) {
break;
}
}
Upvotes: 4