gpt4 book ai didi

java - 从枚举返回计算值

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:39:50 26 4
gpt4 key购买 nike

请问我的问题是两个而且非常简单

  1. 按原样误解枚举

  2. 这个想法在我的代码中缺少一些重要的抽象

代码示例,其中 oprt.calc(x, y) 不可编译,并带有警告 cannot find symbol

public enum Operation {

PLUS {
public double calc(double x, double y) {
return x + y;
}
},
MINUS {
public double calc(double x, double y) {
return x - y;
}
},
MULTILPLE {
public double calc(double x, double y) {
return x * y;
}
},
DIVIDED_BY {
public double calc(double x, double y) {
return x / y;
}
};

public static void main(String args[]) {
double x = 15.25;
double y = 24.50;
for (Operation oprt : Operation.values()) {
System.out.println(x + " " + oprt + " "
+ y + " = " + oprt.calc(x, y));
}
}
}

最佳答案

您错过的是 calc() 方法的抽象声明:

enum Operation {

PLUS {
public double calc(double x, double y) {
return x + y;
}
},
MINUS {
public double calc(double x, double y) {
return x - y;
}
},
MULTILPLE {
public double calc(double x, double y) {
return x * y;
}
},
DIVIDED_BY {
public double calc(double x, double y) {
return x / y;
}
};

**public abstract double calc(double x, double y);**

public static void main(String args[]) {
double x = 15.25;
double y = 24.50;
for (Operation oprt : Operation.values()) {
System.out.println(x + " " + oprt + " "
+ y + " = " + oprt.calc(x, y));
}
}
}

关于java - 从枚举返回计算值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16104728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com