Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You are to write a program name InfixToPostfix.java that converts an infix expre

ID: 3904480 • Letter: Y

Question

You are to write a program name InfixToPostfix.javathat converts an infix expression entered by the user to a postfix expression. The expression may contain the following tokens:
(1)   Integer constants (a series of decimal digits).
(2)   x (representing a value to be supplied later).
(3)   Binary operators (+, -, *, / and %).
(4)   Parentheses
        
Spaces between tokens are allowed but not required. The program will convert the expression to postfix form and display the converted expression. You can consider only single digit for number.

Sample Output:

Enter infix expression: (x + 1) * (x – 2) / 4
Converted expression: x 1 + x 2 - * 4 /

Enter infix expression: 1 2 +
Error in expression!! No operator between operands. Also last token must be an operand.

Enter infix expression: 10.4
Error in expression!! Cannot accept floating point numbers.

Enter infix expression: 1 ( + 2)
Error in expression!! No operator between operand and left parentheses.

Enter infix expression: 5 – (x – 2))
Error in expression!! No matching left parentheses for a right parentheses.

Enter infix expression: 1 ** 2
Error in expression!! The * operator cannot be preceded by a * operator.

Explanation / Answer

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

class InfixToPostfix
{

static int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
  
case '*':
case '/':
return 2;
  
case '^':
return 3;
}
return -1;
}
  
// infix to postfix expression.
static String infixToPostfix(String exp)
{
  
String answer = new String("");

Stack<Character> stack = new Stack<>();

for (int i = 0; i<exp.length(); ++i)
{
char c = exp.charAt(i);

// If operand, add it...
if (Character.isLetterOrDigit(c))
answer += c;
  
// If '(', push it into stack.
else if (c == '(')
stack.push(c);

// If ')', pop and output from the stack ... until '(' get
else if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
answer += stack.pop();

if (!stack.isEmpty() && stack.peek() != '(')
return "Error in expression!!";
else
stack.pop();
}
else
{
while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek()))
answer += stack.pop();
stack.push(c);
}
  
}
  
// poping the all operators...
while (!stack.isEmpty())
answer += stack.pop();
  
return answer;
}
  
public static void main(String args[])
{

// String exp = "a+b*(c^d-e)^(f+g*h)-i";

Scanner scanner = new Scanner(System.in);
String exp = scanner.nextLine();

System.out.println(infixToPostfix(exp));
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote