我想要解析一个算术表达式,在解析后我应该有一个带有值和运算符的bynari树,之后我想用访问者模式进行遍历并得到结果。
我已经解析并构建了树,但每个Node都有足够多的变量:
public class Nod {
public float value = 0;
public String operator =" ";
public int priorityOrder = 0;
public Nod left = null;
public Nod right = null;
public Nod(String operator,int priorityOrder){
this.priorityOrder = priorityOrder;
this.operator = operator;
}
public Nod(float value){
this.value = value;
}
public void setNodLR(Nod left, Nod right){
this.left = left;
this.right = right;
}
}
public class ExpParser {
Stack<Nod> stackRezults = new Stack<Nod>();
Stack<Nod> stackOperators = new Stack<Nod>();
....
// after all instructions .. stackRezults.peek() will give me the root of tree
//without visitor pattern..
public float Evaluate(Nod node){
if( node.right == null && node.left == null)
return node.value;
float leftValue = Evaluate(node.left);
float rightValue = Evaluate(node.right);
switch(node.operator){
case "+" :
return leftValue + rightValue;
break;
// same for others..
}
}
}
//我有一种感觉我无法使用访客模式与我当前的树
我希望每个节点都有变量值或运算符不是两者兼而有之,我已经尝试过泛型......
public class Nod<T> {
T data ;
Nod<T> left = null;
Nod<T> right = null;
public Nod(T data){
this.data = data;
}
public <T> void setNodLR(Nod<T> left , Nod<T> right){
this.left = left;
this.right = right;
}
}
从这里我已经死了..我甚至不能在这个Nod做最后的评估功能..,
//我在这里试了一下
public class Expval {
public <T> float evalExp(String expression){
// i was trying to check if it works.. for expression : 3 + 2
String Vexp[] = expression.split(" ");
Nod<String> root = new Nod<>(Vexp[1]); // here is +
Nod<Float> left = new Nod<>( Float.parseFloat(Vexp[0]) ); // here is 3
Nod<Float> right = new Nod<>(Float.parseFloat(Vexp[2]) ); // here is 2
Radi.setNodRL(left, right);
return 0f;
}
public <T> float Evaluate (Nod<T> Rad){
if(Rad.left == null && Rad.right == null)
return (float)Rad.data; // here i got a error
// Can not cast from T to float
float leftValue = Evaluate(Rad.left);
float rightValue = Evaluate(Rad.right);
// and here 2 wornings Uncheked invocation Evaluate(Nod) of the generic method
Evaluate(Nod<T>) of type ExpParser
// The expression of type Nod needs unchecked conversion to conform to Nod<Object>
switch((String)Rad.data){
case "+" :
return leftValue + rightValue;// if i change float to T i will get here error
break;
}
}
public <T> float Evaluate(Nod<T> node ){
// how can i do this ?
// I mean how do i know if my node contains a string or value
}
如果我走错路告诉我......如果我想和访客一起做,那么树应该是不同的? 他们应该如何访问方法,让EvalVisitor类实现Visitor?