I have to create two stacks and evaluate an infix expression like 3 + 4 + ( 5 -2 ). I have created a code doing it with postfix to create the base since it is easier and it works flawlessly! Now the problem I have is with the parenthesis, I do not know how to check for the parenthesis to be balanced and then if they are evaluate the expression correctly. It should be something like:
Type a balanced infix expression: 5 * (4 + 3)
The result is 35
Type a balanced infix expression: 10 / (2 + 1
Not balanced, try again :
Here is the tester
import java.util.*;
public class InfixTester { //it's postfix at the moment
public static void main(String[] args) {
String expression, retry;
int result;
Scanner scan = new Scanner (System.in);
do {
InfixEvaluator evaluator = new InfixEvaluator(); //in reality is postfix rn
System.out.println ("Type a balanced postfix expression one token at a time:");
expression = scan.nextLine();
result = evaluator.evaluate(expression);
System.out.println();
System.err.println("The result is " + result);
System.out.print("Would you like to continue (y/n)? ");
retry = scan.nextLine();
System.out.println();
}
while (retry.equalsIgnoreCase("y"));
}
}
And here is the evaluator where everything is
import java.util.*;
public class InfixEvaluator { //it's actually postfix right now
private final static char ADD = '+';
private final static char SUBSTRACT = '-';
private final static char MULTIPLY = '*';
private final static char DIVIDE = '/';
private Stack <Integer> stack;
public InfixEvaluator() {
stack = new Stack <Integer>();
}
public int evaluate(String expr) {
int op1, op2, result = 0;
String token;
Scanner parser = new Scanner (expr);
while (parser.hasNext()) {
token = parser.next();
if (isOperator (token)) {
op2 = (stack.pop()).intValue();
op1 = (stack.pop()).intValue();
result = evaluateSingleOperator(token.charAt(0), op1, op2);
stack.push(new Integer (result));
}
else
stack.push(new Integer (Integer.parseInt (token)));
}
return result;
}
private boolean isOperator (String token){
return ( token.equals("+") || token.equals("-") ||
token.equals("*") || token.equals("/"));
}
private int evaluateSingleOperator(char operation, int op1, int op2){
int result = 0;
switch (operation){
case ADD:
result = op1 + op2;
break;
case SUBSTRACT:
result = op1 - op2;
break;
case MULTIPLY:
result = op1 * op2;
break;
case DIVIDE:
result = op1 / op2;
break;
}
return result;
}
}
While all this works just fine for postfix expressions, what do I need to change and add in order to evaluate correctly infix expressions instead? Thanks!