如何编写value()方法



我正在编写一个ArithmeticOperation类,value((方法需要组合左操作数、运算数和右操作数。有人能把它写在公地里吗?

算术运算:算术运算表示两个值之间的算术运算。ArithmeticOperation类型应包含以下枚举类型,以表示该语言的可能操作(如果愿意,您可以自由添加其他运算符(:

公共枚举运算符{Add,Sub,Mult,Div,Rem;}运算符表示+、-、*、/和%运算。ArithmeticOperation类型实例应使用三个参数创建:一个来自上述Operator枚举类型的操作,以及两个表示左操作数表达式和右操作数表达式的表达式。该类型应允许任何具有int/Integer值的语言结构成为可能的表达式。ArithmeticOperation类型应具有以下方法:

value:将状态作为输入,并返回int/Integer值,该值是将运算应用于每个操作数表达式的值的结果。该状态应用于获取表达式的值。toString:应返回一个字符串,该字符串首先包含左操作数的字符串表示,然后是空格、运算符的字符串表示、空格和右操作数的串表示。

public interface Operation {
public enum Operator { Add, Sub, Mult, Div, Rem; }
}
import java.util.*;
import java.io.*;
public class ArithmeticOperation <I> implements Operation{
ArithmeticOperation <Integer> leftoperand = new 
ArithmeticOperation <Integer>();
ArithmeticOperation <Operator> operation = new 
ArithmeticOperation <Operator>();
ArithmeticOperation <Integer> rightoperand = new 
ArithmeticOperation <Integer>(); 

public Integer value(State s){
return leftoperand+operation+rightoperand;
}
public String toString(){
return "("+leftoperand+" , "+operation+", 
"+rightoperand+")";
}    
}


1 error found:
File: /Users/a13875810600/Desktop/ArithmeticOperation.java  [line: 
11]
Error: bad operand types for binary operator '+'
first type:  ArithmeticOperation<java.lang.Integer>
second type: ArithmeticOperation<Operation.Operator>

我想知道现在如何添加Integer类型和Operator类型。这真的值得思考很久。

我想应该是:

public Integer value(State s){
switch (operation) {
case Add:
return leftoperand.value(s) + rightoperand.value(s);
case Sub:
return leftoperand.value(s) - rightoperand.value(s);
case Mul:
return leftoperand.value(s) * rightoperand.value(s);
case Div:
return leftoperand.value(s) / rightoperand.value(s);
case Rem:
return leftoperand.value(s) % rightoperand.value(s);
}
}

相关内容

最新更新