Reputation: 25
To begin with keep in mind that the EXPRESSION is "2 + 3 * 5" and the POSTFIX expression is 2 3 5 * +
Here's a method that I wrote in order to extract the operators and operand from the stack that has the postfix expression, and then evaluate the whole thing.
// This method evaluates the postFix expression
public void evaluateRPN() {
int t1 = 0,
t2 = 0,
calculation = 0;
String oper;
double result;
// Empty stack
Stack stack = new Stack();
// Tokenize expression
Scanner scan = new Scanner(this.postfix);
char current;
while ( scan.hasNext() ) {
String token = scan.next();
if ( this.isNumber(token) ) { // if the token is an operand, push it onto the stack
stack.push(token);
} else { // If the token is an operator
t1 = (char) stack.pop();
t2 = (char) stack.pop();
calculation = (int) evalEx(t2, token, t1 );
stack.push(calculation);
}
}
this.finalExpression = (String) stack.pop();
}
now when I run this code, it gives me an error on the line: t1 = (char) stack.pop(); where I start to pop the first element from the stack. Also the evalEx() method is already declare somewhere else and it works as fine. So my question is, what am I missing here? I know that I should use a try/catch in the (else) part but I don't think that's the problem. Thanks in advanced!
Upvotes: 0
Views: 235
Reputation: 7844
Because you cast a String
object into a char
, and that is not allowed. Unless you are working on a very old java compiler, please use generics. Use Stack<String>
instead of Stack
and you will get the error message at compile time. Also, Stack
is deprecated. Use Deque
instead.
Upvotes: 0