Postfix
The example demonstrate how to calculate the postfix using a stack
This is the postfix class
/* * It calculates the postfix */ /** * * @author JJ */ import java.util.*; import java.text.NumberFormat; import java.text.DecimalFormat; public class PostFix { Stack stack; double sum = 0; NumberFormat formatter = new DecimalFormat("#0.00"); PostFix() { //Creates an empty stack stack = new Stack(); } /* * In this method we will evaluate the values in the stack */ double evaluate(double x, double y, String operator) { if(operator.equals("+")) { sum = x + y; } else if(operator.equals("*")) { sum = x*y; } else if(operator.equals("-")) { sum = x-y; } else if(operator.equals("/")) { if(y==0) { System.out.println("Can't divide by zero"); System.exit(0); } sum = Math.round(x/y); } else { System.out.println("Invalid operator"); System.exit(0); } return sum; } /* * This method determines if we should evaulate or push into the stack */ void determine(String getEle) { Scanner s = new Scanner(getEle).useDelimiter(" "); while(s.hasNext()) { //Check whether the stack is empty or not if(stack.empty()) { if(s.hasNextDouble()) { stack.push(s.nextDouble()); } else { System.out.println("Invalid, first input is an operator"); System.exit(0); } } else { if(s.hasNextDouble()) { stack.push(s.nextDouble()); } else { if(stack.size()<2) { System.out.println("Not enough element in the stack"); System.exit(0); } else { Object lastObjectValue = stack.pop(); double lastValue = Double.parseDouble(lastObjectValue.toString()); Object firstObjectValue = stack.pop(); double firstValue = Double.parseDouble(firstObjectValue.toString()); double getSum = evaluate(firstValue, lastValue, s.next()); stack.push(getSum); } } } } s.close(); if(stack.size() > 1) { System.out.println("There are more than one element in the stack, Invalid"); System.exit(0); } } //Prints out the sum void print() { System.out.println("The sum is " + formatter.format(stack.pop())); } }
Now, lets create a driver to test the postfix class
/* * This is the driver for the postfix */ /** * * @author JJ */ import java.util.*; public class postFixDriver { public static void main(String[] args) { //Create a postfix class object PostFix pf = new PostFix(); //Creates a Scanner object Scanner key = new Scanner(System.in); String getUserInput; //Ask the user for postfix expression System.out.println("Enter the posfix expression: "); getUserInput = key.nextLine(); pf.determine(getUserInput); pf.print(); } }
< Java > <Home>< Java Programs >