Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.util.*;
- import java.util.concurrent.Callable;
- /**
- Calc
- @author R.J. Trenchard 100281657
- @version 19072017-100281657
- @see <a href="https://d2l.langara.bc.ca/d2l/le/calendar/88736/event/2558791/detailsview#2558791">a10: Calculator</a>
- */
- public class Calc implements Callable<Integer> {
- private final Scanner sc;
- private final Deque<Integer> stack;
- /**
- Calc
- @param String anIn an input string to interpret.
- */
- public Calc(String anIn) {
- this(new Scanner(anIn));
- }
- /**
- Calc
- @param Scanner aScanner an input scanner to interpret.
- */
- public Calc(Scanner aScanner) {
- sc = aScanner;
- stack = new LinkedList<Integer>();
- }
- /**
- call
- evaluates the calculation
- @throws RuntimeException when Scanner gives an IO exception
- @throws IllegalArgumentException when an invalid operator is provided
- @throws IllegalStateException if the stack is not a size of one by the end of the calculation, or if the stack runs out of elements.
- @return the final result as type Integer
- */
- public Integer call() throws RuntimeException, IllegalArgumentException, IllegalStateException {
- try {
- while (sc.hasNext()) {
- if (sc.ioException() != null) {
- throw sc.ioException();
- } else if (sc.hasNextInt()) {
- stack.push(sc.nextInt());
- } else {
- stack.push(operate(sc.next(),stack.pop(),stack.pop()));
- }
- }
- if (stack.size() != 1) {
- throw new IllegalStateException("List elements not equal to one");
- }
- }
- catch (IOException e) { // IO exception found in Scanner
- throw new RuntimeException(e);
- }
- catch (IllegalArgumentException e) { // IllegalArgumentException found in operate
- throw new IllegalArgumentException(e);
- }
- catch (NoSuchElementException e) { // NoSuchElementException when stack is empty
- throw new IllegalStateException(e);
- }
- catch (IllegalStateException e) { // IllegalStateException found in stack size
- throw new IllegalStateException(e);
- }
- finally {
- sc.close();
- }
- return stack.pop();
- }
- /**
- operate
- performs an operation
- @param String operator
- @param int i2 the lhs value to operate on
- @param int i1 the rhs value to operate on
- @throws IllegalArgumentException Throws when an invalid operator is given.
- @return the integer result
- */
- private static int operate(String operator, int i2, int i1) throws IllegalArgumentException {
- if (operator.length() == 1) {
- switch (operator.charAt(0)) {
- case '+':
- return i1 + i2;
- case '-':
- return i1 - i2;
- case '*':
- return i1 * i2;
- case '/':
- return i1 / i2;
- case '%':
- return i1 % i2;
- case '^':
- return (int)Math.pow(i1, i2);
- default:
- throw new IllegalArgumentException(operator);
- }
- } else {
- throw new IllegalArgumentException(operator);
- }
- }
- }
Add Comment
Please, Sign In to add comment