Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.mattparks.calculator;
- import java.util.*;
- /**
- * A class that takes inputs from the console and runs calculations.
- */
- public class Calculator {
- private Scanner scanner;
- /**
- * Creates a new calculator.
- */
- public Calculator() {
- scanner = new Scanner(System.in);
- }
- /**
- * Runs the inputs and calculations.
- */
- public void run() {
- // Gets the first value.
- System.out.println("Please enter the first number:");
- double a = scanner.nextDouble();
- // Gets the second value.
- System.out.println("Please enter the second number:");
- double b = scanner.nextDouble();
- // Gets the operation.
- System.out.println("Please enter the operation type:");
- String type = scanner.nextLine();
- if (type.isEmpty()) {
- type = scanner.nextLine();
- }
- // Gets the enum and operation interface,
- Operations operations = getOperation(type);
- if (operations == null) {
- System.out.println("Could not find a operation for " + type);
- System.exit(-1);
- }
- // Runs the calculations and displays results.
- Operation operation = operations.operation;
- double result = operation.calculate(a, b);
- System.out.println(a + " " + operations.shortType + " " + b + " = " + result);
- }
- /**
- * A munch of mathematical operations.
- */
- @SuppressWarnings("unused")
- private enum Operations {
- ADDITION((a, b) -> a + b, "+"), SUBTRACTION((a, b) -> a - b, "-"),
- MULTIPLICATION((a, b) -> a * b, "*"), DIVISION((a, b) -> a / b, "/"),
- POWER((a, b) -> Math.pow(a, b), "^");
- public final Operation operation;
- public final String shortType;
- Operations(Operation operation, String shortType) {
- this.operation = operation;
- this.shortType = shortType;
- }
- }
- /**
- * Gets the operations from a short name.
- *
- * @param shortType The short name.
- *
- * @return The operations found with the short name.
- */
- private static Operations getOperation(String shortType) {
- for (Operations o : Operations.values()) {
- if (o.shortType.equals(shortType)) {
- return o;
- }
- }
- return null;
- }
- /**
- * A interface used to define mathematical operations.
- */
- private interface Operation {
- /**
- * Runs a calculation between two inputs.
- *
- * @param a The first value.
- * @param b The second value.
- *
- * @return The resulting value.
- */
- double calculate(double a, double b);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement