I am working on a project for class. I have to write a program that reads in an infix expression and converts and it to postfix and evaluates it. Currently I have it to where I can convert an infix expression with no parentheses to postfix, but am having some trouble figuring out how to handle parentheses.
import java.util.*;
public class InfToPost
{
private Stack<String> convStack;
private Stack<String> evalStack;
private String infixExp;
private String postfixExp = "";
private int temp;
private int result;
public InfToPost(String exp)
{
String str = "";
infixExp = exp;
convStack = new Stack<String>();
evalStack = new Stack<String>();
for(int i = 0; i < infixExp.length(); i++)
{
str = infixExp.substring(i,i+1);
if(str.matches("[A-Z]|\\d"))
{
postfixExp += str;
}
else if(isOperator(str))
{
if(convStack.isEmpty())
{
convStack.push(str);
}
else
{
String StackTop = convStack.peek();
while(getPrecedence(StackTop,str).equals(StackTop) && !(convStack.isEmpty()))
{
postfixExp += convStack.pop();
if(!(convStack.isEmpty()))
{
StackTop = convStack.peek();
}
}
convStack.push(str);
}
}
}
while(!(convStack.isEmpty()))
{
postfixExp += convStack.pop();
}
System.out.println("Infix:" +" " + infixExp + "\n" + "Postfix:" + " " + postfixExp + "\n" + "Result:" +result);
}
private boolean isOperator(String ch)
{
String operators = "*/%+-";
if(operators.indexOf(ch) != -1)
{
return true;
}
else
{
return false;
}
}
private String getPrecedence(String op1, String op2)
{
String addSub = "+-";
String mulDiv = "*/";
if ((mulDiv.indexOf(op1) != -1) && (addSub.indexOf(op2) != -1))
{
return op1;
}
else if ((mulDiv.indexOf(op2) != -1) && (addSub.indexOf(op1) != -1))
{
return op2;
}
else if((mulDiv.indexOf(op1) != -1) && (mulDiv.indexOf(op2) != -1))
{
return op1;
}
else
{
return op1;
}
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String expression = scanner.nextLine();
new InfToPost(expression);
}
}