开发者

Recursively making/parsing children in Java

I'm trying to parse a tree of nodes recursively, but every child I add evaluates to the last value.

Example: parsing 2+3 should make a node that evaluates 2 and a node that evaluates 3, but instead I get 2 nodes that evaluate to 3.

According to the debugger, subBefore is "2" and subAfter is "3" as it should be.

Constructing a new Operation adds the arguments as children. Why do I end up with children that evaluate to the same value?

Code is below. Term is pretty much the same thing but checks for * and / instead of + and -

Full code:

public class Operation extends ASTNode {

static c开发者_StackOverflow中文版har op; 

  private Operation(ASTNode... n) { super(n); }



  public static Operation parse(String s) {

      String str = s.trim();

    if(Term.parse(str) != null) return new Operation(Term.parse(str));
    else {

// now make substrings

    int lastOpPlus = str.lastIndexOf('+');
    int lastOpMinus = str.lastIndexOf('-');

    if (lastOpPlus > lastOpMinus) {
        op = '+';

        String subAfter = str.substring(lastOpPlus+1);
        String subBefore = str.substring(0, lastOpPlus);

        if(Operation.parse(subBefore)!=null && Term.parse(subAfter) != null) {
            return new Operation(Operation.parse(subBefore), Term.parse(subAfter));
        }

    }

    return null;
    }
  }

  public double eval(java.util.Map<String,Double> symtab) {
    // first check if state is okay checkState();

      if(arity() > 1) { 
          return (getChild(0).eval(symtab)+getChild(1).eval(symtab));
      }
      //System.out.println(arity());
      //getChild(1).eval(symtab);
      else{ 
          return getChild(0).eval(symtab);
      }
  }

}


Hard to tell without seeing the code for Operation.parse, Term.parse, and the Operation constructor, but my guess is that you are sharing a buffer or variable somewhere.

On a separate note, you're doing the parse work twice. It might be good to reorganize your code like this:

Object before = Operation.parse(subBefore); // a more specific type, not Object
Object after = Term.parse(subAfter);
if (before != null && after != null) {
    return new Operation(before, after);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜