在这个称为AClass的类中,我尝试制作一个switch语句,该语句将使用在两个值之间输入的运算符。
public interface Operation {
public enum Operator {Add, Sub, Mult, Div, Rem}
}
import java.util.*;
import java.io.*;
public class AClass<I> implements Operation {
AClass <Integer> leftoperand = new AClass <Integer>();
AClass <Operator> operation = new AClass <Operator>();
AClass <Integer> rightoperand = new AClass <Integer>();
public Integer value (SClass sc) {
switch (operation) {
case Add:
return leftoperand.value(sc) + rightoperand.value(sc);
case Sub:
return leftoperand.value(sc) - rightoperand.value(sc);
case Mult:
return leftoperand.value(sc) * rightoperand.value(sc);
case Div:
return leftoperand.value(sc) / rightoperand.value(sc);
case Rem:
return leftoperand.value(sc) % rightoperand.value(sc);
}
}
public String toString() {
return "(" + leftoperand + "," + operation + "," + rightoperand + ")";
}
}
Error: incompatible types: AClass<AClass.Operator> cannot be converted to int
Error: cannot find symbol
symbol: variable Add
location: class AClass<I>
Error: cannot find symbol
symbol: variable Sub
location: class AClass<I>
Error: cannot find symbol
symbol: variable Mult
location: class AClass<I>
Error: cannot find symbol
symbol: variable Div
location: class AClass<I>
Error: cannot find symbol
symbol: variable Rem
location: class AClass<I>
并且从切换(操作)行开始,我收到了一些错误。我该如何解决这个问题?另外,我可以只将枚举运算符插入AClass内而不使用接口吗?
Java switch语句不支持所有类。从Java文档中,与if-then和if-then-else语句不同,switch语句可以具有许多可能的执行路径。开关适用于byte,short,char和int基本数据类型。它也适用于枚举类型(在Enum Types中讨论),String类以及一些包装某些基本类型的特殊类:Character,Byte,Short和Integer(在Numbers和Strings中讨论)。
AClass <Operator> operation = new AClass <Operator>(); // will not work
Operator operation = Operator.ADD; // will work since operator is an enum;