Randomly choose between of +, -, or * and apply it to two numbers

Good day

I am new to java and would like to know if there is a way for me to randomly choose between multiplication and addition and apply it to two numbers.

Any guidance would be appreciated.

Upvotes: 0

Views: 84

Answers (3)

DevilsHnd - 退した
DevilsHnd - 退した

Reputation: 9192

Place the operators into an array and select a random index value for that array:

String[] operators = {"+", "-", "*", "/"};
int randomOperatorIndex = new java.util.Random().nextInt(operators.length);
int num1 = 24;
int num2 = 12;
double ans = 0.0d;
switch (randomOperatorIndex) {
    case 0:   // + 
        ans = num1 + num2;
        break;
    case 1:   // - 
        ans = num1 - num2;
        break;
    case 2:   // * 
        ans = num1 * num2;
        break;
    case 3:   // / 
        ans = num1 / num2;
        break;
}
 
System.out.println(num1 + " " + operators[randomOperatorIndex] 
                   + " " + num2 + " = " + ans);

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89314

You can put all the possible operations in a List as BinaryOperators, then choose a random index each time.

List<BinaryOperator<Integer>> ops = List.of(Integer::sum, (a,b)->a-b, (a,b)->a*b);
int a = 1, b = 2; // numbers to apply operator to
int result = ops.get(ThreadLocalRandom.current().nextInt(ops.size())).apply(a, b);
System.out.println(result);

Upvotes: 1

robob
robob

Reputation: 1759

I guess a code like the following could work:

// given two number a, b

double rand = Math.random();
if (rand > 0.5)
   c = a*b;
else
   c = a+b;

// c is the result of the addition/multiplication

Upvotes: 1

Related Questions