// Name : Matthew Reeves // This is a program to read and process postfix expressions import java.util.Scanner; import ListPkg.Stack; import ListPkg.LinkedList; import ExceptionPkg.EmptyListException; import java.util.InputMismatchException; public class Postfix { //main method accepts user input to process a postfix expression public static void main( String args[] ) { Scanner input=new Scanner(System.in); Stack stacker=new Stack("testStack"); System.out.println("\nThank you for using the Postfix calculator program!\n"); //creates all necessary instance variables char keepcalc='y'; char oper='q'; double value; Double wrappedValue; Double x; Double y; //this loop continues to run as long as user wants to enter in new postfix expressions do { System.out.print("Please enter an expression in postfix notation to evaluate. \nSeparate all operators/operands with spaces, and end expression with '=':\n\n\t"); //this loops continues to run as long user keeps entering operators/operands for an expression do { try { value=input.nextDouble(); wrappedValue=value; stacker.push(wrappedValue); } catch (InputMismatchException inputMismatchException) { oper=input.next().charAt(0); switch(oper) { case '+': if (stacker.isEmpty()) { continue; } y=(Double)stacker.pop(); if (stacker.isEmpty()) { continue; } x=(Double)stacker.pop(); stacker.push(x+y); continue; case '-': if (stacker.isEmpty()) { continue; } y=(Double)stacker.pop(); if (stacker.isEmpty()) { continue; } x=(Double)stacker.pop(); stacker.push(x-y); continue; case '*': if (stacker.isEmpty()) { continue; } y=(Double)stacker.pop(); if (stacker.isEmpty()) { continue; } x=(Double)stacker.pop(); stacker.push(x*y); continue; case '/': if (stacker.isEmpty()) { continue; } y=(Double)stacker.pop(); if (stacker.isEmpty()) { continue; } x=(Double)stacker.pop(); stacker.push(x/y); continue; case '^': if (stacker.isEmpty()) { continue; } y=(Double)stacker.pop(); if (stacker.isEmpty()) { continue; } x=(Double)stacker.pop(); stacker.push(Math.pow(x,y)); continue; case '=': if (stacker.isEmpty()) { System.out.println("\nInvalid expression entered, cannot evaluate"); continue; } wrappedValue=(Double)stacker.pop(); if (stacker.isEmpty()) { System.out.printf("\n==============================\n\n\tResult = %f\n\n==============================\n\n",wrappedValue); continue; } else { System.out.println("\nInvalid expression entered, cannot evaluate"); continue; } } } }while(oper!='='); input.nextLine(); System.out.print("\n--------------------------------------------------\nWould you like to enter a new expression? (Y/N) "); keepcalc=input.next().charAt(0); System.out.print("--------------------------------------------------\n\n"); stacker.Clear(); oper='q'; }while(keepcalc=='y' || keepcalc=='Y'); } }