java用for循环直接遍历输出枚举四则运算
时间: 2024-06-10 17:04:53 浏览: 80
您好!关于您的问题,Java中可以通过for循环和switch语句遍历输出枚举四则运算。以下是示例代码:
```java
public enum Operator {
ADD("+"),
SUBTRACT("-"),
MULTIPLY("*"),
DIVIDE("/");
private String symbol;
Operator(String symbol) {
this.symbol = symbol;
}
public String getSymbol() {
return this.symbol;
}
}
public class Main {
public static void main(String[] args) {
for (Operator operator : Operator.values()) {
switch (operator) {
case ADD:
System.out.println("加法运算: " + operator.getSymbol());
break;
case SUBTRACT:
System.out.println("减法运算: " + operator.getSymbol());
break;
case MULTIPLY:
System.out.println("乘法运算: " + operator.getSymbol());
break;
case DIVIDE:
System.out.println("除法运算: " + operator.getSymbol());
break;
default:
break;
}
}
}
}
```
在上述代码中,我们首先定义了一个枚举类型Operator,它包含四个枚举值,分别表示加法、减法、乘法和除法运算。然后,我们使用for循环和switch语句遍历输出每个枚举值对应的运算符号。希望这个例子能够帮到您。
阅读全文