猿问

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

 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?


慕婉清6462132
浏览 105回答 2
2回答

喵喵时光机

尝试切换: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);}

DIEA

我将运算符逻辑(分辨率和评估)封装到 .喜欢enumenum 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;    }}这简化了 中的逻辑,只需解析运算符并对其进行求值即可。喜欢mainOper o = Oper.from(operator);System.out.printf("The %s result is %d%n", o.name().toLowerCase(), o.eval(num1, num2));
随时随地看视频慕课网APP

相关分类

Java
我要回答