2

乱数と演算子を作成するためにこのコードを作成しましたが、どのように計算して結果を表示できますか?

たとえば、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++;
        }
    }

}
4

3 に答える 3

1

これは、式を左から右に計算する(比較的) 単純なコードです(操作の順序を考慮していないため、正しい ではなく3+4*5として評価されます)。(3+4)*53+(4*5)

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

    for (int i = 0; i < 3; i++) {
        int randNum = r.nextInt(9) + 1; // 1 - 9 inclusive
        if (i != 0) {
            operator = operators[r.nextInt(operators.length)];
            System.out.print(operator);
            result = calculate(result, randNum, operator);
        }
        else {
            result = randNum;
        }
        System.out.print(randNum);
    }
    System.out.println("=" + result);
}
public static int calculate(int operand1, int operand2, String operator) {
    switch (operator) {
        case "+":
            return operand1 + operand2;
        case "-":
            return operand1 - operand2;
        case "*":
            return operand1 * operand2;
        default:
            throw new RuntimeException();
    }
}
于 2013-10-09T17:31:12.223 に答える