为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕婉清6462132 2022-08-17 10:22:50
 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 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

尝试切换:


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);

}


查看完整回答
反对 回复 2022-08-17
?
DIEA

TA贡献1820条经验 获得超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));



查看完整回答
反对 回复 2022-08-17
  • 2 回答
  • 0 关注
  • 104 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信