【问题标题】:Mathematical operations with an operator variable - Java带有运算符变量的数学运算 - Java
【发布时间】:2018-09-26 20:31:25
【问题描述】:

我有两个int 类型的变量(称为int1int2)和一个变量类型char(它总是保存一个数学运算符,称为op)。如何对这三个变量进行数学运算?我必须手动做,因为老师的原因我不能使用ScriptEngineManager

我不能做int res = int1 + op + int2 因为它添加了变量op 在ascii 表中的值。 如何将这三个变量放在一起根据变量 op 进行数学运算?

我发现的最简单的方法如下:

int res = 0;
if (op == '+'){res=int1+int2;}
else if (op == '-'){res = int1-int2;}
else if (op == '*'){res = int1*int2;}
else {res = int1/int2;}

还有比这更优雅的方式吗?谢谢!

【问题讨论】:

  • 答案是不,没有。您可以使用 switch 语句而不是 if/else,但您仍然需要为每个运算符创建一个单独的分支。
  • 在我看来你是在正确的轨道上。继续前进并保持良好的工作。

标签: java math operators


【解决方案1】:

创建一个将操作字符映射到两个整数的函数的枚举。

enum Operator {
    ADD('+',(x,y)->x+y),
    SUBTRACT('-',(x,y)->x-y),
    MULTIPLY('*',(x,y)->x*y),
    DIVIDE('/',(x,y)->x/y),
    REMAINDER('%',(x,y)->x%y),
    POW('^',(x,y)->(int)Math.pow(x,y));

    char symbol;
    BiFunction<Integer,Integer,Integer> operation;

    Operator(final char symbol, final BiFunction<Integer,Integer,Integer> operation) {
        this.symbol = symbol;
        this.operation = operation;
    }

    public static Operator representedBy(final char symbol)
    {
        return Stream.of(Operator.values()).filter(operator->operator.symbol==symbol).findFirst().orElse(null);
    }

    public Integer apply(final int x,final int y)
    {
        return operation.apply(x,y);
    }
}

public static void main(final String[] args) {
    final char op = '+';
    final int int1 = 1;
    final int int2 = 2;
    final Operator operator = Operator.representedBy(op);
    if (operator == null)
    {
        // handle bad character
    }
    else
    {
        System.out.println(operator.apply(int1,int2));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    相关资源
    最近更新 更多