2

I created this code to create random numbers and operators, but how can it calculate and show the result?

What it does now is for example print out: 4+1-3 or 9*2-8 etc. I don't know how to calculate the result of 4+1-3 or 9*2-8 and print it out.

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++;
        }
    }

}
MOTIVECODEX
  • 2,624
  • 14
  • 43
  • 78
  • Should 3+4*5 be evaluated in the correct way? – Tim S. Oct 09 '13 at 17:15
  • @Tim S, no not yet, that's going to be my next step, but first I want to fix this problem and see if I can continue – MOTIVECODEX Oct 09 '13 at 17:16
  • @davecom, it's not a duplicate, and as ciemborg is saying on that post: "running JS engine for that is "quite" over the top". I already have that part that it randomizes everything. I just need to calculate it, so it's not an duplicate. – MOTIVECODEX Oct 09 '13 at 17:19
  • It is a duplicate, Tim S's answer is very similar to some of the lesser voted answers in that other question. You should Google more next time... – davecom Oct 09 '13 at 17:43
  • '{' is similar to '}' but's it's not the same. – MOTIVECODEX Oct 09 '13 at 18:15

3 Answers3

4

That is not a simple questions because you must keep in mind the priority of arithmetical operators, so my guess is you must use a mathematical library that helps you. For example, Formula4j: http://www.formula4j.com/index.html

angel_navarro
  • 1,757
  • 10
  • 11
  • I already have that part I can use for the right priority, I just need to calculate it as it is for now – MOTIVECODEX Oct 09 '13 at 17:17
  • If you see the "Example" section of this library, you'll is realy easy to use and it can calculate directly the result from a string that contains your formula – angel_navarro Oct 09 '13 at 17:24
1

Are you stuck applying operations to arguments?

The simplest way:

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

A slightly more extensible way that uses a hash table instead of an endless 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);
  ...
}

If you think this is needlessly long, it is. Still something like this is the typical pattern in Java-land. (That's why Scala exists, but it's another story.)

This does not even touch operation priority or parentheses.

9000
  • 39,899
  • 9
  • 66
  • 104
1

This is some (relatively) simple code that will calculate the expression left-to-right (it doesn't take into account the order of operations, so 3+4*5 is evaluated as (3+4)*5, not the correct 3+(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();
    }
}
Tim S.
  • 55,448
  • 7
  • 96
  • 122