java实现四则运算switch
时间: 2024-09-25 15:01:11 浏览: 49
在Java中,可以使用`switch-case`语句实现简单的四则运算,但是由于Java不支持直接对数值类型做算术运算后的条件判断,通常我们会创建一个枚举或者利用if-else结构来完成这个任务。这里以一个基础的加法运算为例:
```java
public enum Operation {
ADD {
@Override
public int perform(int a, int b) {
return a + b;
}
},
SUBTRACT {
@Override
public int perform(int a, int b) {
return a - b;
}
},
MULTIPLY {
@Override
public int perform(int a, int b) {
return a * b;
}
},
DIVIDE {
@Override
public double perform(int a, int b) {
if (b != 0) {
return (double) a / b;
} else {
throw new ArithmeticException("Cannot divide by zero");
}
}
};
abstract public int perform(int a, int b);
}
// 使用示例
public static void main(String[] args) {
int num1 = 5;
int num2 = 3;
Operation operation = Operation.ADD; // 可以根据需要切换操作
switch (operation) {
case ADD:
System.out.println(num1 + " + " + num2 + " = " + operation.perform(num1, num2));
break;
case SUBTRACT:
System.out.println(num1 + " - " + num2 + " = " + operation.perform(num1, num2));
break;
case MULTIPLY:
System.out.println(num1 + " * " + num2 + " = " + operation.perform(num1, num2));
break;
case DIVIDE:
System.out.println(num1 + " / " + num2 + " = " + operation.perform(num1, num2));
break;
}
}
```
在这个例子中,`Operation`枚举包含了四个成员,每个成员都有一个对应的`perform`方法来处理对应的运算。然后通过`switch`根据选择的`Operation`调用对应的方法。
阅读全文