0

I am trying to read a file line by line and take action on every line that begins with the character 'Q'. I keep getting this error after trying many solutions from SO and the JavaDoc. I cannot figure out for the life of me what I am getting it. My method looks like this:

public Question makeQuestion(){
    //scanner checks line and takes action
    while(fileScan.hasNextLine()){

        //save the line
        String line = fileScan.nextLine();

        //if line is blank move on to next line
        if(line.isEmpty()) fileScan.nextLine();

        //if line starts with Q do something
        if(line.charAt(0) == 'Q'){
            System.out.println(line);
        }

    }

The method finds the first line that begins with Q but fails after that. What could I be doing wrong?

eignhpants
  • 1,611
  • 4
  • 26
  • 49
  • `if(line.isEmpty()) fileScan.nextLine();` What if the nextLine is also empty / null?. What if there is no next line? BTW what is the error?. – TheLostMind Oct 01 '14 at 13:45

4 Answers4

0

You don't want to execute a send nextLine() within your loop.

Try this:

while(fileScan.hasNextLine()){

    //save the line
    String line = fileScan.nextLine();

    //if line is NOT empty AND starts with Q do something
    if(!line.isEmpty() && line.charAt(0) == 'Q'){
        System.out.println(line);
    }

}
Dave Leo
  • 28
  • 4
0
public Question makeQuestion(){
    //scanner checks line and takes action
    while(fileScan.hasNextLine()){

        //save the line
        String line = fileScan.nextLine();


        //if line starts with Q do something
        if(line != null && !line.isEmpty() && line.charAt(0) == 'Q'){
            System.out.println(line);
        }

}

If you call nextLine in the loop twice it is possible that you reach the last line in your first call.

in that case, the second call will throw the exception because there is no next line.

Philipp Sander
  • 10,139
  • 6
  • 45
  • 78
0

You should not read the line again if it is empty.

public Question makeQuestion(){
//scanner checks line and takes action
while(fileScan.hasNextLine()){

    //save the line
    String line = fileScan.nextLine();

    //if line starts with Q do something
    if(!line.isEmpty() && line.charAt(0) == 'Q'){
        System.out.println(line);
    }

}
jrochette
  • 1,117
  • 5
  • 22
0

Your logic here,

if(line.isEmpty()) fileScan.nextLine();

is incorrect (for one thing, it doesn't update line so you then output blank lines). The easiest solution is probably to use,

if(line.isEmpty()) continue;
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249