Advertisement
Guest User

Untitled

a guest
Mar 2nd, 2015
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. import java.util.Stack;
  2.  
  3. public class Counter {
  4.    
  5.     private Stack<Double> undoLog;
  6.     private Stack<Double> redoLog;
  7.    
  8.     private double counter;
  9.    
  10.     public Counter() {
  11.         counter = 0;
  12.         undoLog = new Stack<Double>();
  13.         redoLog = new Stack<Double>();
  14.     }
  15.    
  16.     public double getCounter() {
  17.         return counter;
  18.     }
  19.    
  20.     public void count(String input) {
  21.         if(input.equals("undo") && !undoLog.isEmpty()) {
  22.             redoLog.push(counter);
  23.             counter = undoLog.peek().doubleValue();
  24.             undoLog.pop();
  25.             System.out.println("Counter = " + counter);
  26.             return;
  27.         } else if(input.equals("redo") && !redoLog.isEmpty()) {
  28.             undoLog.push(counter);
  29.             counter = redoLog.peek().doubleValue();
  30.             redoLog.pop();
  31.             System.out.println("Counter = " + counter);
  32.             return;
  33.         } else if(input.equals("end")) {
  34.             return;
  35.         }
  36.         char operation = ' ';
  37.         double value = 0;
  38.         try {
  39.             value = Integer.parseInt(input.substring(1));
  40.             operation = input.charAt(0);
  41.         } catch (NumberFormatException e) {
  42.             System.out.println("You must input a number as a value.");
  43.             return;
  44.         } catch (StringIndexOutOfBoundsException se) {
  45.             System.out.println("You must use the correct format: operation|value. Ex. +346");
  46.             return;
  47.         }
  48.         undoLog.push(counter);
  49.         handleOperation(operation, value);
  50.         System.out.println("Counter = " + counter);
  51.     }
  52.    
  53.     private void handleOperation(char operation, double value) {
  54.         redoLog.clear();
  55.         switch(operation) {
  56.         case '*':
  57.         case 'x':
  58.             counter *= value;
  59.             break;
  60.         case '/':
  61.             counter /= value;
  62.             break;
  63.         case '+':
  64.             counter += value;
  65.             break;
  66.         case '-':
  67.             counter -= value;
  68.             break;
  69.         default:
  70.             System.out.println("You must use the correct format: operation|value. Ex. +346");
  71.             break;
  72.         }
  73.     }
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement