我正在编写一个 ArithmeticOperation 类,value() 方法需要组合左操作数、运算和右操作数。有人可以在公共(public)空间写它吗?
ArithmeticOperation:ArithmeticOperation 表示两个值之间的算术运算。 ArithmeticOperation 类型应包含以下枚举类型来表示该语言可能的操作(如果您愿意,您可以自由添加其他运算符):
公共(public)枚举运算符 { 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);
}
}
关于java - 如何编写 value() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58601612/