如何用Java计算结果?

时间:2013-10-09 17:13:37

标签: java math random

我创建了这段代码来创建随机数和运算符,但是如何计算和显示结果呢?

现在做的是例如打印输出:4 + 1-3或9 * 2-8等。 我不知道如何计算4 + 1-3或9 * 2-8的结果并打印出来。

public static void main(String[] args) {
    int t = 0;
    String[] operators = {"-", "+", "*"};
    String operator;
    Random r = new Random();

    for (int i = 0; i < 3; i++) {
        int randNum = randNums(9, 1);
        operator = operators[r.nextInt(operators.length)];
        System.out.print(randNum);
        if (t < 2) {
            System.out.print(operator);
            t++;
        }
    }

}

3 个答案:

答案 0 :(得分:4)

这不是一个简单的问题,因为你必须牢记算术运算符的优先级,所以我猜你必须使用一个可以帮助你的数学库。例如,Formula4j: http://www.formula4j.com/index.html

答案 1 :(得分:1)

您是否坚持将操作应用于参数?

最简单的方法:

if ("+".equals(operator)) {
  result = arg1 + arg2;
} else if ...
System.out.println("See, " + arg1 + operator + arg2 " = " + result);

使用哈希表而不是无限if的稍微可扩展的方式:

import java.util.*;

// Poor man's first-class function
interface BinaryOp {
  int apply(int arg1, int arg2);
}

final static BinaryOp ADD = new BinaryOp() {
  public int apply(int arg1, int arg2) { return arg1 + arg2; }
}

final static BinaryOp SUBTRACT = new BinaryOp() {
  public int apply(int arg1, int arg2) { return arg1 - arg2; }
}

final static BinaryOp MULTIPLY = new BinaryOp() {
  public int apply(int arg1, int arg2) { return arg1 * arg2; }
}

static final Map<String, BinaryOp> OPERATIONS = new HashMap<String, BinaryOp>();

// This replaces the 'if', easier to extend.
static {
  OPERATIONS.put("+", ADD);
  OPERATIONS.put("-", SUBTRACT);
  OPERATIONS.put("*", MULTIPLY);
}

public static void main(String[] args) {
  ...
  BinaryOp operation = OPERATIONS.get(operation_name);
  int result = operation.apply(arg1, arg2);
  ...
}

如果你认为这是不必要的长,那就是。这样的事情仍然是Java-land中的典型模式。 (这就是Scala存在的原因,但这是另一个故事。)

这甚至不会触及操作优先级或括号。

答案 2 :(得分:1)

这是一些(相对)简单的代码will calculate表达式从左到右(它没有考虑操作的顺序,所以3+4*5被评估为{{1} },而不是正确的(3+4)*5):

3+(4*5)
相关问题