Infix to Postfix

verruckt24 1 Tallied Votes 1K Views Share

I have seen several posters asking for help on programs converting an Infix expression to a Postfix one. I have written a program to convert a simple Infix expression to a Postfix one so that people here can be directed towards some sample code from which they get the idea to writing one. I have also provided comments describing what the code part is supposed to do in that block, the idea here is to discourage blind copying and to encourage the understanding of the program. Once the idea behind such a program is undestood, even a beginner can write one for himself.
There can be many ways in which a particular solution can be implemented, this impementation is based on .
Lastly I want to mention why I call this program one that converts a simple Infix expression. Thats because I haven't written it to take into consideration complex expressions with paranthesis in them, also I haven't written it for an exhaustive list of operators (the operators I have taken into account are mentioned in the source code). Programmers can take an hint from this simple program and add their own additions to it.

package alok.examples;

import java.util.Scanner;
import java.util.Stack;

/*
 * This is a code snippet to convert a simple Infix Expression to a Postfix one.
 * NOTE : It would not work for expressions containing paranthesis. It only takes into 
 * account operators for the following operations:
 * 1. Multiplication
 * 2. Division
 * 3. Modulus
 * 4. Addition
 * 5. Subtraction
 * 
 * The precedence of the operations is shown below. Lower level operations have a higher 
 * precedence, so here, operations in Level 1 have higher precedence than those mentioned
 * in Level 2. 
 * Operations mentioned in the same level have equal precedence.
 *  
 * Level 1. Multiplication, Division, Modulus
 * Level 2. Addition, Subtraction  
 */
public class Infix2Postfix {
	
	private Stack<String> stack;
	private String infixExp;
	private String postfixExp = "";
	
	public Infix2Postfix(String exp){
		
		String str = "";
		infixExp = exp;
		stack = new Stack<String>();
		
		for (int i=0;i<infixExp.length();i++){
			/* 
			 * If the character is a letter or a digit we append it to the postfix 
			 * expression directly. 
			 */
			str = infixExp.substring(i,i+1);
			if(str.matches("[a-zA-Z]|\\d"))
				postfixExp += str;
			else if (isOperator(str)){
				/*
				 * If the stack is empty we directly push the current char into it.
				 */
				if (stack.isEmpty()){
					stack.push(str);
				}
				else{
					/*
					 * If the current character is an operator, we need to check the stack 
					 * status then, if the stack top contains an operator with lower
					 * precedence, we push the current character in the stack else we pop
					 * the character from the stack and add it to the postfix string. This 
					 * continues till we either find an operator with lower precedence in the 
					 * stack or we find the stack to be empty.
					 */
					String stackTop = stack.peek();
					while (getPrecedence(stackTop,str).equals(stackTop)&& !(stack.isEmpty())){
						postfixExp += stack.pop();
						if (!(stack.isEmpty()))
							stackTop = stack.peek();
					}
					stack.push(str);
				}
			}
		}
		// In the end just append all the operators from the stack to the postfix expression.
		while(!(stack.isEmpty()))
			postfixExp += stack.pop();
		// Print out the postfix expression
		System.out.println("The postfix form of the expression you entered is: " + postfixExp);
	}
	
	/*
	 * Returns true if 'ch' is an operator, false o/w
	 */ 
	private boolean isOperator(String ch){
		
		String operators = "*/%+-";
		if (operators.indexOf(ch) != -1)
			return true;
		else
			return false;
	}
	
	/*
	 * Returns the operator with higher precedence among 'op1' & 'op2', if they have equal
	 * precedence, the first operator in the argument list (op1) is returned.
	 */ 
	private String getPrecedence(String op1, String op2){
		
		String multiplicativeOps = "*/%";
		String additiveOps = "+-";
		
		if ((multiplicativeOps.indexOf(op1) != -1) && (additiveOps.indexOf(op2) != -1))
			return op1;
		else if ((multiplicativeOps.indexOf(op2) != -1) && (additiveOps.indexOf(op1) != -1))
			return op2;
		else if((multiplicativeOps.indexOf(op1) != -1) && (multiplicativeOps.indexOf(op2) != -1))
			return op1;
		else 
			return op1;
	}		
	
	public static void main(String[] args){
		
		System.out.println("Enter an expression in the Infix form:");
		Scanner scanner = new Scanner(System.in);
		
		String expression = scanner.nextLine();
		new Infix2Postfix(expression);
	}
}

Dani AI

Generated

Practical fixes first (addresses the errors raised by and ). The NoClassDefFoundError comes from the package line: either keep the package alok.examples; and compile/run from the project root with the matching folder structure (for example javac alok/examples/Infix2Postfix.java then java -cp . alok.examples.Infix2Postfix), or remove the package declaration. The constructor error is a name mismatch: the constructor must have the same name as the class. If you renamed the class to InfixToPostfix also rename the constructor, or change the new call to new Infix2Postfix(...). pointed to this already; these exact commands should remove the runtime/compile confusion.

Practical improvements to the algorithm and robustness. Tokenize the input into multi-character operands, operators and parentheses (numbers, identifiers, '(', ')', '+', '-', '*', '/', '%', '^'). Use a numeric precedence map and the standard rule: while stack not empty AND precedence(top) >= precedence(curr) pop to output (use a special rule for right-associative operators like ^). Push '(' and on ')' pop until '(' is found. Emit tokens separated by spaces so multi-digit numbers stay unambiguous. Prefer Deque<String> (ArrayDeque) and StringBuilder over legacy Stack and repeated string concatenation.

Testing and edge cases. Add checks for mismatched parentheses, invalid tokens and unary operators (detect a unary minus at expression start or after '('). Example expected outputs: 12+34 -> 12 34 +, a+b*(c-d) -> a b c d - * +. These small tests catch the usual pitfalls quickly and make the example from easier to extend.

apc00008 0 Newbie Poster

Exception in thread "main" java.lang.NoClassDefFoundError: Infix2Postfix (wrong
name: alok/examples/Infix2Postfix)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:12
4)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
Could not find the main class: Infix2Postfix. Program will exit.

peter_budo 2,532 Code tags enforcer Team Colleague Featured Poster

, that is because you just copied and pasted code without checking actual code. Otherwise you would have spotted there is package alok.examples; You have two options:
A)Observe package requirement and create relevant folder structure
B)Remove package from start of program

Anonymous123 0 Newbie Poster

I'm getting an error on the very last line that says:
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor InfixToPostfix(String) is undefined

at InfixToPostfix.main(InfixToPostfix.java:62)"

How can I fix this?

verruckt24 438 Posting Shark

Method is Infix2Postfix instead of InfixToPostfix

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.