Advertisement
lmohanarun

x java.util.Stack

Oct 17th, 2015
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.company.onp;
  2.  
  3. import com.company.stack.Stack;
  4. java.util.stack
  5.  
  6. public class ONP {
  7.     Stack stack = new Stack();
  8.  
  9.     public ONP(String[] args) throws OnpWrongInputException {
  10.         for(int j=args.length-1; j>=0; j--){
  11.             try {
  12.                 Double num = Double.parseDouble(args[j]);
  13.                 addDouble(num);
  14.             }
  15.             catch (Exception e){
  16.                 new Addition().addToONP(this, args[j]);
  17.                 new Subtraction().addToONP(this, args[j]);
  18.                 new Division().addToONP(this, args[j]);
  19.                 new Multiplication().addToONP(this, args[j]);
  20.             }
  21.         }
  22.     }
  23.  
  24.     public Double calculate() throws OnpWrongInputException {
  25.         Double value = 0.0;
  26.         try {
  27.             while(true) {
  28.                 Double firstNumber = (Double) stack.pop();
  29.                 Double secondNumber = (Double) stack.pop();
  30.                 Operation operation = (Operation) stack.pop();
  31.                 value = operation.calculate(firstNumber, secondNumber);
  32.                 stack.push(value);
  33.             }
  34.         }catch (Stack.EndOfTheStackException e){
  35.             return value;
  36.         }catch (ClassCastException e){
  37.             throw new OnpWrongInputException();
  38.         }
  39.     }
  40.  
  41.     protected void addOperation(Operation operation){
  42.         stack.push(operation);
  43.     }
  44.  
  45.     private void addDouble(Double number){
  46.         stack.push(number);
  47.     }
  48.  
  49.     private static class OnpWrongInputException extends Exception {
  50.     }
  51.  
  52.     public static void main(String[] args) {
  53.         try {
  54.             ONP onp = new ONP(args);
  55.             System.out.println(onp.stack.toString());
  56.             System.out.println(onp.calculate());
  57.         } catch (Exception e) {
  58.             e.printStackTrace();
  59.         }
  60.     }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement