0

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
Puppy
  • 144,682
  • 38
  • 256
  • 465

1 Answers1

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

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I thought that strings were interned and thus any two Strings with the same value will have the same reference. – Puppy Aug 11 '10 at 12:14
  • 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 Aug 11 '10 at 12:28
  • @DeadMG: the following is true: `"{" == "{"`, but `"{" == new String("{")` definitely not. That's what is happening here. – BalusC Aug 11 '10 at 12:42
  • 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. – Puppy Aug 11 '10 at 12:50