Professional Documents
Culture Documents
Scanner;
import java.util.Stack;
class InfixToPostfix
{
switch (s)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
return -1;
// to postfix expression.
char c = exp.charAt(i);
if (Character.isLetterOrDigit(c))
result += c;
else if (c == '(')
stack.push(c);
// If the scanned character is an ')', pop and output from the stack
else if (c == ')')
{
result += stack.pop();
else
stack.pop();
else
// an operator is encountered
{
char t=exp.charAt(i+1);
if(t=='+'||t=='-'||t=='/'||t=='*')
return "Invalid Expression";
while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek()))
result += stack.pop();
stack.push(c);
}
while (!stack.isEmpty())
result += stack.pop();
return result;
}
// Driver method
{
Scanner scan = new Scanner(System.in);
while(testcases!=0)
{
String exp=scan.nextLine();
System.out.println(infixToPostfix(exp));
testcases--;