John John - 2 months ago 14
Java Question

Java - Scanner.nextLine() skipping even when accounting for new line

I'm trying to read from a file line by line that is tab delimited. Here's an example of a file:

state 0 start
state 5 accept
transition 0 0 1 x R
transition 1 0 0 x R


I create a
Scanner
object for the file and set the delimiter to
\t
. I loop through the file as long as there is a next line. I want to check whether a line begins with
state
or
transition
and then get the following information. In the case of lines that begin with
state
, I use
nextInt()
and then
next()
to obtain
0
and
start
respectively. The issue then arises of going to the next line and repeating the process. I use
nextLine()
and that's where things get ugly.

I'm aware that
nextLine()
does not consume the newline character, so I thought to use it twice and it creates more of an issue it seems.

Scanner sc = new Scanner(file);
sc.useDelimiter("\t");

while(sc.hasNextLine())
{
if(sc.next().equals("state") == true)
{
int stateNumber = sc.nextInt();
String state = sc.next();
sc.nextLine();
}
sc.nextLine();
}


That seems to be the relveant code that is creating issues.

Am I misunderstanding how
next()
works or am i missing something else entirely?

Answer

One option here would be to simply read in each entire line in one go, and then split by a delimeter (tab) to get the individual components:

which (sc.hasNextLine()) {
    String line = sc.nextLine();
    String[] parts = line.split("\\t");

    if (parts[0].equals("state")) {
        // construct custom object here
    }
}

If you want to stick with your original approach then use this:

while(sc.hasNextLine()) {
    if (sc.next().equals("state")) {
        int stateNumber = sc.nextInt();
        String state = sc.next();
    }

    // consume the entire remaining line, line break included
    sc.nextLine();
}

For those lines containing "state" you were making two calls to nextLine(), which would result in an entire line being lost.

Comments