tags:

views:

57

answers:

1

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.

+2  A: 
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:

BalusC
I thought that strings were interned and thus any two Strings with the same value will have the same reference.
DeadMG
That's only true for Strings that are the result of constant expressions, for example, literals in your code. See the Java language spec, 3rd edition, 3.10.5.
Thomas Kappler
@DeadMG: the following is true: `"{" == "{"`, but `"{" == new String("{")` definitely not. That's what is happening here.
BalusC
It didn't occur to me that the condition failing when it shouldn't would also produce the problem that I had. Thanks for this correct answer.
DeadMG