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);
}
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));
添加回答
举报