Puppy
Puppy

Reputation: 146900

scanner.nextLine() doesn't actually give the next line

I've written a pretty simple recursive-descent parser in Java, but having some issues with the scanner I've attached to the file.

private void ParseDataFields(Controller.TreeData data, java.util.Scanner scanner) {
        java.lang.String nextline;
        while(scanner.hasNextLine()) {
            nextline = scanner.nextLine().trim();
            if (nextline == "{") { // If we are with this, we are a new Child object declaration.
                if (data.CanHaveChildren()) {
                    ParseDataFields(data.CreateNewChild(), scanner);
                    continue;
                } else
                    FileValidationError("Attempted to give a child object to a data node that could not have one.");
            }
            if (nextline.endsWith("}")) // End of Child object data declaration
                return;
            ... parse the line

The problem is that when { is found, the method recurses, but the next line isn't actually taken (there is a next line). It just gives back the same { token, which is not valid.

I've been using a sample file to test this out:

Name = scumbag
{
    Name = lolcakes
}
}

Used reflection and I confirmed that the field=value syntax is working fine. But the opening token for a new child isn't.

Upvotes: 0

Views: 2767

Answers (1)

BalusC
BalusC

Reputation: 1108537

if (nextline == "{") { 

Comparing strings in Java should be done with String#equals().

if (nextline.equals("{")) {

Strings are objects in Java, not primitives. The == would compare objects by reference, not by value.

See also:

Upvotes: 2

Related Questions