Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Stack;
- public class Counter {
- private Stack<Double> undoLog;
- private Stack<Double> redoLog;
- private double counter;
- public Counter() {
- counter = 0;
- undoLog = new Stack<Double>();
- redoLog = new Stack<Double>();
- }
- public double getCounter() {
- return counter;
- }
- public void count(String input) {
- if(input.equals("undo") && !undoLog.isEmpty()) {
- redoLog.push(counter);
- counter = undoLog.peek().doubleValue();
- undoLog.pop();
- System.out.println("Counter = " + counter);
- return;
- } else if(input.equals("redo") && !redoLog.isEmpty()) {
- undoLog.push(counter);
- counter = redoLog.peek().doubleValue();
- redoLog.pop();
- System.out.println("Counter = " + counter);
- return;
- } else if(input.equals("end")) {
- return;
- }
- char operation = ' ';
- double value = 0;
- try {
- value = Integer.parseInt(input.substring(1));
- operation = input.charAt(0);
- } catch (NumberFormatException e) {
- System.out.println("You must input a number as a value.");
- return;
- } catch (StringIndexOutOfBoundsException se) {
- System.out.println("You must use the correct format: operation|value. Ex. +346");
- return;
- }
- undoLog.push(counter);
- handleOperation(operation, value);
- System.out.println("Counter = " + counter);
- }
- private void handleOperation(char operation, double value) {
- redoLog.clear();
- switch(operation) {
- case '*':
- case 'x':
- counter *= value;
- break;
- case '/':
- counter /= value;
- break;
- case '+':
- counter += value;
- break;
- case '-':
- counter -= value;
- break;
- default:
- System.out.println("You must use the correct format: operation|value. Ex. +346");
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement