public static void main(String [] args){ Scanner keyboard = new Scanner(System.in);//to read input from the user Stack stack = new Stack(); //to push user input into the stack if it is a number String input = ""; //to save user input into a variable int tempVar = 0; //to save a poped number for calculation System.out.println("\nWelcome To The Postfix Calculator!");//printing message for the user do{ //ask user to enter a value System.out.print("\nEnter a number or an arthmetic operator, or 0 to display the result: "); input = keyboard.nextLine(); //put user input into a variable /*If input is "+" the last two elements in the stack are poped and their addition * is pushed into the stack*/ if(input.equals("+")){ tempVar = (int)stack.pop(); tempVar = (int)stack.pop() + tempVar; stack.push(tempVar); } /*If input is "-" the last two elements in the stack are poped and their subctraction * is pushed into the stack*/ else if(input.equals("-")){ tempVar = (int)stack.pop(); tempVar = (int)stack.pop() - tempVar; stack.push(tempVar); } /*If input is "*" the last two elements in the stack are poped and their multiplication * is pushed into the stack*/ else if(input.equals("*")){ tempVar = (int)stack.pop(); tempVar = (int)stack.pop() * tempVar; stack.push(tempVar); } /*If input is "/" the last two elements in the stack are poped and their division * is pushed into the stack*/ else if(input.equals("/")){ tempVar = (int)stack.pop(); tempVar = (int)stack.pop() / tempVar; stack.push(tempVar); } /*If input is none of these and not "0" then the number is parsed and pushed into the * stack*/ else if(!input.equals("0")) stack.push(Integer.parseInt(input)); } while(!input.equals("0")); if(stack.empty()) System.out.println("\nYou haven't entered any value, please try again."); else System.out.println("\nFinal Value: " + stack.pop()); }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)