这个java计算器程序可以更简化吗?

时间:2012-11-01 11:25:47

标签: java code-cleanup

我是java的初学者,这是一个简单的计算器代码,我是在教程的帮助下完成的。这很好用,但正如你可以看到他们在这个程序中没有“构造函数”!而他们只是一个扫描仪对象! 这个程序是否可以通过具有结构和方法的方式进行简化,作为我学习的一个例子?

import java.util.Scanner; 
public class apples {
public static void main(String args[]){
    Scanner calculator = new Scanner(System.in);
    double fnum, snum, answer;

    System.out.println("Enter first number: ");
    fnum = calculator.nextDouble();
    System.out.println("Enter second number: ");
    snum = calculator.nextDouble();
    System.out.println("enter any operator: ");
    String op = calculator.next();
    switch (op){
    case ("x") :
        answer = fnum * snum;
        System.out.println(answer);
        break;

    case ("/") :
        answer = fnum / snum;
    System.out.println(answer);
    break;

    case ("+") :
        answer = fnum + snum;
    System.out.println(answer);
    break;

    case ("-") :
        answer = fnum - snum;
    System.out.println(answer);
    break;


    }

    }





}

2 个答案:

答案 0 :(得分:1)

一个想法可能是使用更多功能样式来减少冗余操作符和丑陋的案例切换,并使代码更易于维护:

import java.util.*;
public class apples {
    protected static final Map<String, BinOp> operators = new HashMap<String, BinOp>() {{
        put("+", new BinOp() { public double calc(double op1, double op2) { return op1 + op2; }; });
        put("-", new BinOp() { public double calc(double op1, double op2) { return op1 - op2; }; });
        put("x", new BinOp() { public double calc(double op1, double op2) { return op1 * op2; }; });
        put("/", new BinOp() { public double calc(double op1, double op2) { return op1 / op2; }; });
    }};
    public static void main(String args[]){
        Scanner calculator = new Scanner(System.in);
        double fnum, snum, answer;

        System.out.println("Enter first number: ");
        fnum = calculator.nextDouble();
        System.out.println("Enter second number: ");
        snum = calculator.nextDouble();
        System.out.println("enter any operator: ");
        String op = calculator.next();
        BinOp opFunction = operators.get(op);
        answer = opFunction.calc(fnum, snum);
        System.out.println(answer);
    }
}

interface BinOp {
    double calc(double op1, double op2);
}

当然,您应该在输入或不存在的运算符中处理不是double值。

另一个好主意是分离逻辑:

import java.util.*;
public class apples {
    public static void main(String args[]){
        Scanner calculator = new Scanner(System.in);
        double fnum, snum, answer;

        System.out.println("Enter first number: ");
        fnum = calculator.nextDouble();
        System.out.println("Enter second number: ");
        snum = calculator.nextDouble();
        System.out.println("enter any operator: ");
        String op = calculator.next();
        answer = calc(op, fnum, snum);
        System.out.println(answer);
    }

    public static double calc(String op, double op1, double op2) {
        switch (op) {
            case ("+"): return op1 + op2;
            case ("-"): return op1 - op2;
            case ("x"): return op1 * op2;
            case ("/"): return op1 / op2;
        }
        throw new RuntimeException("Not implemented!");
    }
}

它使您的代码更具可读性和可维护性。

因为我真的很喜欢枚举:

import java.util.*;
public class apples {
    public static void main(String args[]){
        Scanner calculator = new Scanner(System.in);
        double fnum, snum, answer;

        System.out.println("Enter first number: ");
        fnum = calculator.nextDouble();
        System.out.println("Enter second number: ");
        snum = calculator.nextDouble();
        System.out.println("enter any operator: ");
        String op = calculator.next();
        Operation operator = Operation.get(op);
        answer = operator.calc(fnum, snum);
        System.out.println(answer);
    }
}

enum Operation {
    ADD("+") {
        public double calc(double op1, double op2) {
            return op1 + op2;
        }
    },
    SUB("-") {
        public double calc(double op1, double op2) {
            return op1 - op2;
        }
    },
    MUL("x") {
        public double calc(double op1, double op2) {
            return op1 * op2;
        }
    },
    DIV("/") {
        public double calc(double op1, double op2) {
            return op1 / op2;
        }   
    },
    ;

    Operation(String op) {
        this.op = op;
    }
    protected String op;
    public abstract double calc(double op1, double op2);
    public static Operation get(String op) {
        for (Operation operation : values()) {
            if (operation.op.equals(op)) {
                return operation;
            }
        }
        throw new RuntimeException("Not implemented!");
    }
}

您也可以在其他地方使用:

answer = Operation.MUL(2, 3);

轻松迭代所有操作,获取名称等。

答案 1 :(得分:0)

<强>已更新---------------------------------

这是我的解决方案;):

启动程序(例如,也可以来自servlet,无论你想要什么):

  public class Launcher {

    private final Scanner scanner;

    public Launcher(Scanner scanner) {
        this.scanner = scanner;
    }

    public Scanner getScanner() {
        return scanner;
    }

    public static void main(String args[]) {
        Launcher launcher = new Launcher(new Scanner(System.in));
        launcher.printResult(launcher.takeOperandInput("first"), launcher.takeOperandInput("second"),
                launcher.takeOperatorInput());
    }

    private String takeOperandInput(String operandNumber) {
        askForOperand(operandNumber);
        return getElement();
    }

    private void askForOperand(String operand) {
        System.out.println("Enter " + operand + " :");
    }

    private String takeOperatorInput() {
        askForOperator();
        return getElement();
    }

    private void askForOperator() {
        System.out.println("enter any operator (+,-,/,*): ");
    }

    private String getElement() {
        return scanner.next();
    }

    private void printResult(String leftOperand, String rightOperand, String operator) {
        Calculator calculator = new Calculator(leftOperand, rightOperand, operator);
        System.out.println(calculator.calculate());
    }
}

这里是Calculator类:

public class Calculator {

    private final Operands operands;

    private final OperationType operationType;

    public Calculator(String leftOperand, String rightOperand, String operationType) {
        this.operands = new Operands(leftOperand,  rightOperand);
        this.operationType = OperationType.transform(operationType);;
    }

    public double calculate() {
        return operationType.calculate(operands);
    }
}

这里是不可变的Operands类:

final class Operands {

    private final double leftOperand;

    private final double rightOperand;

    public Operands(String leftOperand, String rightOperand) {
        this.leftOperand = Double.parseDouble(leftOperand);
        this.rightOperand = Double.parseDouble(rightOperand);
    }

    public final double getLeftOperand() {
        return leftOperand;
    }

    public final double getRightOperand() {
        return rightOperand;
    }
}

这里包含逻辑的OperationType枚举:

enum OperationType {

    ADDITION("+") {
        public double calculate(Operands operands) {
            return operands.getLeftOperand() + operands.getRightOperand();
        }
    },
    SUBTRACTION("-") {
        public double calculate(Operands operands) {
            return operands.getLeftOperand() - operands.getRightOperand();
        }
    },
    MULTIPLICATION("*") {
        public double calculate(Operands operands) {
            return operands.getLeftOperand() * operands.getRightOperand();
        }
    },
    DIVISION("/") {
        public double calculate(Operands operands) {
            return operands.getLeftOperand() / operands.getRightOperand();
        }
    };

    private String operationType;

    private OperationType(String operationType) {
        this.operationType = operationType;
    }

    abstract double calculate(Operands operands);

    static OperationType transform(String operationType) {
        for (OperationType ot : values()) {
            if (ot.operationType.equals(operationType)) {
                return ot;
            }
        }
        throw new IllegalArgumentException("Unknown operator, please redo your operation.");
    }
}