Write a java program to evaluate postfix expressions containing complex numbers using a stack. The algorithm for evaluating a postfix expression requires a stack of complex numbers. The pseudocode for evaluating postfix expressions is given below:
while not end of expression
switch next token
case complex number:
push the value onto the stack
case operator:
pop two operands from the stack
evaluate operation
push result onto the stack
pop the final result off the stack
Each complex number will all be enclosed in a pair of parentheses. The operators permitted include +, - and *. You may assume that all expressions are syntactically correct.
The user should be allowed to enter and evaluate any number of expressions.
Here is what I have done so far:
import java.io.*;
import java.util.Stack;
import java.util.Scanner;
public class stack {
public static void main(String[] args) {
Stack pstack = new Stack();
Stack pstack2 = new Stack();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a value: ");
String result = input.nextLine();
Integer.parseInt(result);
pstack.push(result);
//System.out.println(pstack);
for (int i=0; i < result.length(); i++){
char ch = result.charAt(i);//Checks the characters
switch(ch)
{
case '+':
int x,y;
int op1 = ((Integer)(pstack.pop())).intValue();
int op2 = ((Integer)(pstack.pop())).intValue();
pstack.push(new Integer(op2 + op1));
System.out.println(pstack);
break;
case '-':
int op1 = ((Integer)(pstack.pop())).intValue();
int op2 = ((Integer)(pstack.pop())).intValue();
pstack.push(new Integer(op2 - op1));
break;
case '*':
int op1 = ((Integer)(pstack.pop())).intValue();
int op2 = ((Integer)(pstack.pop())).intValue();
pstack.push(new Integer(op2 * op1));
System.out.println(pstack);
break;
case '/':
int op1 = ((Integer)(pstack.pop())).intValue();
int op2 = ((Integer)(pstack.pop())).intValue();
pstack.push(new Integer(op2 / op1));
System.out.println(pstack);
break;
}
//System.out.println(pstack);
}
}
}