In: Computer Science
Convert an infix expression to its postfix representation in JAVA
Java program to convert infix to postfix expression:
**************************************************************************************************************************************************
import java.util.Stack;
import java.util.Scanner;
public class Main {
//precedence function to return the precedence of the
operators
static int precedence(char c){
switch (c){
case '+': //when + or - give precedence 1
case '-':
return 1;
case '*'://when / and * give precedence 2
case '/':
return 2;
case '^': //when ^ give precedence 3
return 3;
}
return -1;
}
//function to convert infix to postfix
static String infixToPostFix(String expression){
String result = ""; //String result to show the result
Stack<Character> stack = new Stack<>(); //making a
stack class object haivng Character
for (int i = 0; i <expression.length() ; i++) { //taking a loop
for the expression
char c = expression.charAt(i); //Character c at i position
//check if char is operator
if(precedence(c)>0){
while(stack.isEmpty()==false &&
precedence(stack.peek())>=precedence(c)){
result += stack.pop();
}
stack.push(c);
}else if(c==')'){ //when there is )
char x = stack.pop(); //pop from the stack
while(x!='('){
result += x;
x = stack.pop();
}
}else if(c=='('){
stack.push(c);
}else{
//character is neither operator nor (
result += c;
}
}
for (int i = 0; i <=stack.size() ; i++) {
result += stack.pop();
}
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the Infix Expression: "); //prompt the user
for input of the expression
String exp = input.nextLine(); //take input
System.out.println("Postfix Expression: " +
infixToPostFix(exp));//call the infixToPostFix method and print
it
}
}
**********************************************************************************************************************************************
Screenshot of the code for further reference:
Output: