Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Infix to Postfix Converter

843789Oct 10 2009 — edited Oct 11 2009
Hello,

I have the following code and it works fine. The converter works correctly but only if there is a space between the characters; therefore, it can't handle inputs with multiple digits (e.g., 34).
How can I modify this code so that there does not have to be a space between each character.

Example:

Currently the program will only run if there is a space between input character. Example: ( 5 * 2 ) / ( 2 * 1 )

However, the program should be able to handle expressions like: (300+23)*(43-21)/(84+7) -- see, with multiple digit numbers like 300

Thank you.
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;


public class ExpressionEvaluator
{
	// initialize two stacks: operator and operand
	private static Stack operatorStack = new Stack();
	private static Stack operandStack = new Stack();
	
	// method converts infix expression to postfix notation
	private static String toPostfix(String infix)
	{
		StringTokenizer s = new StringTokenizer(infix);
		// divides the input into tokens for input
		String symbol, postfix = "";
		while (s.hasMoreTokens())
		// while there is input to be read
		{
			symbol = s.nextToken();
			// if it's a number, add it to the string
			if (Character.isDigit(symbol.charAt(0)))
				postfix = postfix + "" + (Integer.parseInt(symbol));
			else if (symbol.equals("("))
			// push "("
			{
				Character operator = new Character('(');
				operatorStack.push(operator);
			}
			else if (symbol.equals(")"))
			// push everything back to "("
			{
				while (((Character)operatorStack.peek()).charValue() != '(')
				{
					postfix = postfix + " " + operatorStack.pop();
				}
				operatorStack.pop();
			}
			else
			// print operatorStack occurring before it that have greater precedence
			{
				while (!operatorStack.empty() && !(operatorStack.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(((Character)operatorStack.peek()).charValue()))
					postfix = postfix + " " + operatorStack.pop();
				Character operator = new Character(symbol.charAt(0));
				operatorStack.push(operator);
			}
		}
		while (!operatorStack.empty())
			postfix = postfix + " " + operatorStack.pop();
		return postfix;
	}
	
	// method evaulates postfix expression
	private static int evaluate(String postfix)
	{
		StringTokenizer s = new StringTokenizer(postfix);
		// divides the input into tokens for input
		int value;
		String symbol;
		while (s.hasMoreTokens())
		{
			symbol = s.nextToken();
			if (Character.isDigit(symbol.charAt(0)))
			// if it's a number, push it onto stack
			{
				Integer operand = new Integer(Integer.parseInt(symbol));
				operandStack.push(operand);
			}
			else // if it's an operator, operate on the previous two popped operandStack items
			{
				int op2 = ((Integer)operandStack.pop()).intValue();
				int op1 = ((Integer)operandStack.pop()).intValue();
				int result = 0;
				switch(symbol.charAt(0))
				{
					case '*': {result = op1 * op2; break;}
					case '+': {result = op1 + op2; break;}
					case '-': {result = op1 - op2; break;}
					case '/': {result = op1 / op2; break;}
					case '%': {result = op1 % op2; break;}
				}
				Integer operand = new Integer(result);
				operandStack.push(operand);
			}
		}
		value = ((Integer)operandStack.pop()).intValue();
		return value;
	}
	
	// method compares operators to establish precedence
	private static int prec(char x)
	{
		if (x == '+' || x == '-')
			return 1;
		if (x == '*' || x == '/' || x == '%')
			return 2;
		return 0;
	}
	public static void main(String args[]) throws IOException
	{
		String infix;
	
		// Enter an infix equation option
		infix = JOptionPane.showInputDialog(null, "Enter an Infix Expression:"); 
		
		// displays the postfix answer
		JOptionPane.showMessageDialog(null, "Converted to a Postfix Expression: " + toPostfix(infix));
		
		
		// Evaluates the expression 
		JOptionPane.showMessageDialog(null, "The answer is: " + evaluate(toPostfix(infix)));
		
	}

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 8 2009
Added on Oct 10 2009
6 comments
574 views