|
-
February 2nd, 2009, 01:43 PM
#1
parsing prefix expression small bug?
hello there! i have created this parser in java which reads expressions in the form of ( + 4 4 ) and
( + ( + 4 4 ) 4 ) it reads them and gives the correct result but it doesnt give me the correct result for expressions like these:
( + 4 ( + 4 4 ) )
which are just a minor variation. it gives me 16 instead of 12 when i try and parse this type of expression. it probably adds an extra 4 somewhere but i cant find where. could someone try to help me fix it. heres the code that takes the expression as a String and evaluates it (please note that im keeping it simple only number 4 and + operators are allowed)
the psuedo version:
calc():
while not the end of the expression
read in a token
if the token is an operator, push it on the ops stack
else if it is a number, push it on the values stack
else if it is an open paren,
calc() the sub-expression recursively
else if it is a close paren,
pop the current function of the ops stack
check how many arguments the op takes, and
pop that many values off of the values stack
calculate the result of the op and push it on the stack
return
else
print an error message and exit (or throw an exception, your choice, though this is not quite an exceptional thing)
my code converted from the psuedo version:
Code:
public int evaluate(String exp) {
int result = 0;
String[] expr = exp.split(" ");
int i = 0;
while (i <= expr.length -1) {
String token = expr[i];
if (token.equals("+")) {
opStack.push(expr[i]);
} else if (token.equals("4")) {
valueStack.push(expr[i]);
} else if (token.equals("(")) {
ArrayList<String> res2 = new ArrayList<String>();
ArrayList<String> arr= new ArrayList<String>();
String newExpr = "";
for (String s : expr) {
arr.add(s);
}
res2.addAll(arr.subList(i+1, arr.size() -1));
for (String a : res2) {
newExpr = newExpr + a + " ";
}
evaluate(newExpr);
} else if (token.equals(")")) {
String op = (String) opStack.pop();
int n1 = Integer.parseInt((String) valueStack.pop());
int n2 = Integer.parseInt((String) valueStack.pop());
result = n1 + n2;
valueStack.push("" + result);
} else {
System.err.println("Invalid Expression!");
}
i++;
}
return result;
}
t basically doesnt calculate expressions which have a number after the operator AND and an open bracket. e.g.
( + 4 ( + 4 4 ) )
any ideas?? thanks guys!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|