Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company.onp;
- import com.company.stack.Stack;
- java.util.stack
- public class ONP {
- Stack stack = new Stack();
- public ONP(String[] args) throws OnpWrongInputException {
- for(int j=args.length-1; j>=0; j--){
- try {
- Double num = Double.parseDouble(args[j]);
- addDouble(num);
- }
- catch (Exception e){
- new Addition().addToONP(this, args[j]);
- new Subtraction().addToONP(this, args[j]);
- new Division().addToONP(this, args[j]);
- new Multiplication().addToONP(this, args[j]);
- }
- }
- }
- public Double calculate() throws OnpWrongInputException {
- Double value = 0.0;
- try {
- while(true) {
- Double firstNumber = (Double) stack.pop();
- Double secondNumber = (Double) stack.pop();
- Operation operation = (Operation) stack.pop();
- value = operation.calculate(firstNumber, secondNumber);
- stack.push(value);
- }
- }catch (Stack.EndOfTheStackException e){
- return value;
- }catch (ClassCastException e){
- throw new OnpWrongInputException();
- }
- }
- protected void addOperation(Operation operation){
- stack.push(operation);
- }
- private void addDouble(Double number){
- stack.push(number);
- }
- private static class OnpWrongInputException extends Exception {
- }
- public static void main(String[] args) {
- try {
- ONP onp = new ONP(args);
- System.out.println(onp.stack.toString());
- System.out.println(onp.calculate());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement