我正在编写ArithmeticOperation类,并且value()方法需要组合左操作数,操作和右操作数。谁能写在公地?

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

公共枚举运算符{添加,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>


我想知道如何立即添加整数类型和运算符类型。长时间考虑确实值得。

最佳答案

我猜应该是:

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);
    }
}

07-26 03:52