执行正确的代码后,如何停止执行每个println的代码?

时间:2019-03-17 19:13:53

标签: java

    Scanner scan = new Scanner(System.in);

    System.out.print("Enter 2 numbers: ");
    int num1 = scan.nextInt();
    int num2 = scan.nextInt();
    System.out.println("Numbers Saved! Choose your operator + - * / ");
    String operator = scan.next();
    int result;

    result = (operator.equals("+")) ? (num1 + num2) : (num1);
    System.out.println("The addition result is " +result);
    result = (operator.equals("-")) ? (num1 - num2) : (num1);
    System.out.println("The subtraction result is " +result);
    result = (operator.equals("*")) ? (num1 * num2) : (num1);
    System.out.println("The multiplication result is " +result);
    result = (operator.equals("/")) ? (num1 / num2) : (num1);
    System.out.println("The division result is " +result);



}

} 这是我的简单计算器代码,例如,当我选择+选项时,它将运行所有System.out.println行,如何防止它执行此操作,而仅执行与运算符匹配的println?

2 个答案:

答案 0 :(得分:3)

尝试切换:

switch (operator) {
    case "+":
        result = num1 + num2;
        System.out.println("The addition result is " + result);
        break;
    case "-":
        result = num1 - num2;
        System.out.println("The subtraction result is " + result);
        break;
    case "-":
        result = num1 * num2;
        System.out.println("The multiplication result is " + result);
        break;
    case "/":
        result = num1 / num2;
        System.out.println("The integer division result is " + result);
        break;
    default:
        throw IllegalArgumentException("Unsupported operator: " + operator);
}

答案 1 :(得分:2)

我会将操作符逻辑(解析度和评估值)封装enum中。喜欢,

enum Oper {
    ADDITION("+"), SUBTRACTION("-"), MULTIPLICATION("*"), DIVISION("/");
    Oper(String symbol) {
        this.symbol = symbol;
    }

    public int eval(int a, int b) {
        switch (this) {
        case ADDITION: return a + b;
        case SUBTRACTION: return a - b;
        case MULTIPLICATION: return a * b;
        case DIVISION: return a / b;
        }
        return -1;
    }

    private String symbol;

    public static Oper from(String operator) {
        for (Oper o : values()) {
            if (o.symbol.equals(operator)) {
                return o;
            }
        }
        return null;
    }
}

这简化了main中的逻辑,只需解析运算符并对其进行评估。喜欢,

Oper o = Oper.from(operator);
System.out.printf("The %s result is %d%n", o.name().toLowerCase(), o.eval(num1, num2));