aa

mail@pastecode.io avatar
unknown
java
2 years ago
2.1 kB
6
Indexable
Never
/**
 *
 *  @author Gacoń Rafał S22522
 *
 */

package zad1;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class Calc {
    public String doCalc(String cmd) {
        final String errorMsg = "Invalid command to calc";
        String[] arr = cmd.split("\\s+");

        BigDecimal number1, number2;
        String operator;

        try {
            operator = arr[1];
            number1 = new BigDecimal(arr[0]);
            number2 = new BigDecimal(arr[2]);
        } catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
            return errorMsg;
        }

        Map<String, Calculation> m = new HashMap<>() {{
            put("+", new AddCalculation());
            put("-", new SubtractCalculation());
            put("/", new DivideCalculation());
            put("*", new MultiplyCalculation());
        }};

        try {
            return m.get(operator).calculate(number1, number2);
        } catch (NullPointerException e) {
            return errorMsg;
        }
    }

    interface Calculation {
        String calculate(BigDecimal number1, BigDecimal number2);
    }

    static class AddCalculation implements Calculation {
        public String calculate(BigDecimal number1, BigDecimal number2) {
            return number1.add(number2).toString();
        }
    }

    static class SubtractCalculation implements Calculation {
        public String calculate(BigDecimal number1, BigDecimal number2) {
            return number1.subtract(number2).toString();
        }
    }

    static class DivideCalculation implements Calculation {
        public String calculate(BigDecimal number1, BigDecimal number2) {
            DecimalFormat format = new DecimalFormat("0.#######");
            return format.format(number1.divide(number2, 7, RoundingMode.HALF_EVEN));
        }
    }

    static class MultiplyCalculation implements Calculation {
        public String calculate(BigDecimal number1, BigDecimal number2) {
            return number1.multiply(number2).toString();
        }
    }

}