In: Computer Science
Write a class PostFix that has one method covert that converts an infix expression (as a string input) to a postfix. Then Test it in a different class. code in java.
import java.util.Stack;
class PostFix{
// Higher returned value means higher precedence
static int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
// The main method that converts given infix expression
public static String infixToPostfix(String exp)
{
String result = new String("");
Stack <Character>stack = new Stack<>();
for (int i = 0; i<exp.length(); ++i)
{
char c = exp.charAt(i);
// If the scanned character is an operand, add it to output.
if (Character.isLetterOrDigit(c))
result += c;
// If the scanned character is an '(', push it to the stack.
else if (c == '(')
stack.push(c);
else if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
result += stack.pop();
if (!stack.isEmpty() && stack.peek() != '(')
return "Invalid Expression"; // invalid expression
else
stack.pop();
}
else
{
while (!stack.isEmpty() && Prec(c) <=
Prec(stack.peek()))
result += stack.pop();
stack.push(c);
}
}
// pop all the operators from the stack
while (!stack.isEmpty())
result += stack.pop();
return result;
}
}
public class TestPostFix {
public static void main(String[] args) {
System.out.println(PostFix.infixToPostfix("a+b*(c^d-e)^(f+g*h)-i"));
}
}
NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.
I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME