1 Attachment(s)
Prefix to Expression tree
I am trying to make a basic java program that takes an infix expression as the argument (i.e. "+ * 2 - 7 3 / 20 5") and outputs it as an arithmetic expression tree and evaluates the tree.
i have the attached classes to work with...am really struggling on this one so any help would be appreciated.
Attachment 1877
Re: Prefix to Expression tree
so far i have this
Code:
public class ArithmeticTreeTest {
public static void main(String[] args) throws IOException {
BinaryTreeNode tree = null;
String preFix = args[0];
StringTokenizer st = new StringTokenizer(preFix);
while (st.hasMoreTokens()){
String tokens = st.nextToken();
System.out.println(tokens);
try{
int num = Integer.parseInt(tokens);
if (tree.left() == null){
tree.setLeft(new BinaryTreeNode(new Integer(num)));
} else {
tree.setRight(new BinaryTreeNode(new Integer(num)));
}
} catch (NumberFormatException e){
char operator = tokens.charAt(0);
tree = new BinaryTreeNode(operator, null, null);
}
}
System.out.println();
System.out.println("The tree representation is:");
System.out.println(tree.toString());
System.out.println();
System.out.println("The tree evaluates to " + evaluate(tree));
System.out.println();
}
protected static int evaluate(BinaryTreeNode node){
if (BinaryTreeNode.size(node)==1)
return ((Integer) node.value()).intValue();
else {
int left=evaluate(node.left());
int right=evaluate(node.right());
char c=((Character) node.value()).charValue();
switch (c){
case '+': return (left+right);
case '*': return (left*right);
case '-': return (left-right);
case '/': return (left/right);
case '%': return (left%right);
default: { System.out.println("Unknown operator!");
System.exit(-1); return 0;}
}
}
}
}
Re: Prefix to Expression tree
Bump, need help with this too.
Re: Prefix to Expression tree
Maybe you'll find one of my blog articles useful; it babbles about expression compilation and the code can do what you want (and some more).
kind regards,
Jos
Re: Prefix to Expression tree
Thanks for the help, that's all a bit advanced for me i don't really understand most of it...