[英]mathematical expressions as enum type JAVA
我只想知道我是否定义
public enum Op {-,+}
我可以挑出其中一个进行数学运算,例如4 +Op[0] +3
会返回1
而不是4-3
,但是它也在询问标识符
enum
是java
一种特殊的class ( type)
,它可以包含称为常量的实例字段以及方法。 定义常量名的方式使java
定义字段的规则变得紫罗兰。 一个字段必须具有某些字符,包括az,AZ,_(在score之下)。 因此,不允许将算术符号用作常量名称。
其次,当您在此处调用4+Op[0]+3
,您会将操作数与plus(符号)串联在一起,并期望得到整数值! 它不是您可以在Java中期望的方式。 看起来像运算符重载..但Java不支持运算符重载。
在下面的示例中,您可以根据需要重载Calculator.execute()
。 例如,要获得浮点结果,您可以执行以下操作:
public float execute(float a , Op op, float b ){
float f=0.0f;
// TODO
return f;}...
这是您要在java中实现的解决方案之一:
public class EnumTest
{
public static void main (String []args)
{
Calculator c=new Calculator();
int a=c.execute(4, Op.PLUS,3);
System.out.println("4 +Op.PLUS +3="+a);
a=c.execute(4, Op.MINUS, 3);
System.out.println("4 +Op.MINUS+3="+a);
// prints
// 4 +Op.PLUS +3=7
// 4 +Op.MINUS +3=1
}
}
enum Op{MINUS, PLUS,MULTIPLY,DIVIDE};
class Calculator
{
public int execute (int operandA, Op op, int operandB)
{
int a=0;
switch(op)
{
case MINUS:
a=operandA-operandB;
break;
case PLUS:
a=operandA+operandB;
break;
case MULTIPLY:
a=operandA*operandB;
break;
case DIVIDE:
if(operandB>0) // avoid devideByZero exception
a=operandA/operandB;
break;
}
return a;
}
}
这是我能想到的最接近的:
enum Op implements IntBinaryOperator {
minus((i,j) -> i-j),plus((i,j) -> i+j);
@Override
public int applyAsInt(int left, int right) {
return op.applyAsInt(left, right);
}
final IntBinaryOperator op;
Op(IntBinaryOperator op) {
this.op = op;
}
}
像这样使用它:
IntBinaryOperator op = Op.minus;
int one = op.applyAsInt(4,3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.