Question
If the input infix expression is valid, then the function should return a string representing the corresponding postfix expression However, if the input infix expression is not valid, there are four error messages that may also be returned: 1. 'imbalanced brackets' (if the parentheses are not balanced) 2. 'invalid symbol' (if any token is not a valid operator, integer, or bracket) 3. 'too many operators' (if the number of operators is greater than or equal to the number of operands) 4. 'too few operators' (if the number of operators is more than one less than the number of operands) Examples of each of these are shown below The following code: print (generate postfix('24
Explanation / Answer
import java.io.*; class Stack { char a[]=new char[100]; int top=-1; void push(char c) { try { a[++top]= c; } catch(StringIndexOutOfBoundsException e) { System.out.println("Stack full , no room to push , size=100"); System.exit(0); } } char pop() { return a[top--]; } boolean isEmpty() { return (top==-1)?true:false; } char peek() { return a[top]; } } public class InfixToPostfix { static Stack operators = new Stack(); public static void main(String argv[]) throws IOException { String infix; //create an input stream object BufferedReader keyboard = new BufferedReader (new InputStreamReader(System.in)); //get input from user System.out.print(" Enter the algebraic expression in infix: "); infix = keyboard.readLine(); //output as postfix System.out.println("The expression in postfix is:" + toPostfix(infix)); } private static String toPostfix(String infix) //converts an infix expression to postfix { char symbol; String postfix = ""; for(int i=0;i