I have written a program to perform an infix to postfix conversion. I'm getting an empty stack exception, I can't seem to figure out where it goes empty.
Thank you in advabce for your time.
Code:
package prog17_12;
import java.util.Scanner;
import java.util.Stack;
public class InfixToPostfixConverter
{
//take out the infix and change it into postfix
public static StringBuffer convertToPostfix(StringBuffer infix)
{
Stack<Character> charStack = new Stack<Character>();
StringBuffer temporary = new StringBuffer("");//to store the postfix expression
//push a left paren onto the stack and add a right paren to infix
charStack.push('(');
infix.append(')');
//convert the infix expression to postfix
for (int infixCount = 0; !charStack.isEmpty(); ++infixCount)
{
if (Character.isDigit(infix.charAt(infixCount)))
temporary.append(infix.charAt(infixCount) + " ");
else if (infix.charAt(infixCount) == '(')
charStack.push('(');
else if (isOperator(infix.charAt(infixCount)))
{
while ( isOperator(stackTop(charStack)) &&
precedence(stackTop(charStack), infix.charAt(infixCount)))
temporary.append(charStack.pop() + " ");
charStack.push(infix.charAt(infixCount));
}//end else if
else if (infix.charAt(infixCount) == ')')
{
while (isOperator(stackTop(charStack)) || stackTop(charStack) == '(')
{
if (isOperator(stackTop(charStack)))
temporary.append(charStack.pop() + " ");
else
charStack.pop();
}//end while
} // end else if
}//end for
return temporary;
}//end method convertToPostfix
//checks to see character is an operator
public static boolean isOperator(char c)
{
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '%')
return true;
else
return false;
}//end method isOperator
//determines if first operator(a) has equal or greater precedence over operator(b)
public static boolean precedence(char a, char b)
{
String operatorString = "^*/%+-";
if (operatorString.indexOf(a) >= operatorString.indexOf(a))
return true;
else
return false;
}//end method precedence
//returns the top value of the stack without popping the stack
public static Character stackTop(Stack<Character> stack)
{
return (stack.peek());
}//end stackTop
public static void main(String args[])
{
StringBuffer infix = new StringBuffer();
Scanner input = new Scanner(System.in);
//get mathematical expression from user
System.out.println("Please input a mathematical expression");
infix.append(input.next());
System.out.println(convertToPostfix(infix).toString());
}
}//InfixToPostfixConverter
here is the exception
Code:
Please input a mathematical expression
8+3-5
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Unknown Source)
at prog17_12.InfixToPostfixConverter.stackTop(InfixToPostfixConverter.java:73)
at prog17_12.InfixToPostfixConverter.convertToPostfix(InfixToPostfixConverter.java:37)
at prog17_12.InfixToPostfixConverter.main(InfixToPostfixConverter.java:85)