Casting a primitive type into an operator....

Hello, I'm working on an assignment for my programming class which involves reading a mathematical expression from the user, checking to see if parentheses are balanced, changing the expression to postifx expression, and finally evaluate the postfix expression and print the result.

It's the last part that I'm currently stuck in. So far the program does everything but the evaluation, which is actually not a difficult process. Here is my code so far:

void ReversePostfixNotation()

{

stk.clear();

Scanner sc =new Scanner(postfix);

int t1 = -1;

int t2 = -1;

int t3 = -1;

try

{

while(sc.hasNext())

{

String current = sc.next();

if(isNumber(current))

{

stk.push(current);

}

elseif(isOperator(current.charAt(0)))

{

char operator = current.charAt(0);

t1 = Integer.parseInt((String) stk.pop());

t2 = Integer.parseInt((String) stk.pop());

// STUCK HERE

// Need to have: t2 (operator) t1

}

}

}

Where the STUCK HERE comment is written, I need to be able to cast the operator primitive type into an ACTUAL operator. All the other methods used are written and working, and the operator variable is guaranteed to be either +,-,/, or *.

Thanks in advance, let me know if I can clear anything else up.

[2048 byte] By [Luis2101a] at [2007-11-27 10:08:18]
# 1

Well you don't need to cast anything. You will need to use a stack.

Read your postfix equation.

If current token is an operator

pop two values off the stack

perform the operation (ie + means addition etc)

push result back onto stack

else

current token is a value so push it onto the stack

floundera at 2007-7-13 0:44:47 > top of Java-index,Java Essentials,New To Java...
# 2

You could just switch on your operator variableswitch (operator) {

case '+':

// do addition

// push result onto stack

break;

case '-': //etc ...

}

dwga at 2007-7-13 0:44:47 > top of Java-index,Java Essentials,New To Java...