mfarberg
mfarberg

Reputation: 55

Randomly choose between calling two methods

I am creating a math game for my son that follows a story. I have two methods that will present him with a question. The first is named subtraction and second is named addition. Currently I just call a method at a certain point in the story, but I would prefer to randomly chose either the subtraction or addition method so it is less predictable.

Upvotes: 2

Views: 1210

Answers (2)

barbarossa
barbarossa

Reputation: 129

Adding to the answer of Mureinik:

You could also use the Random class in order to choose between more than two methods, in case you'd want to add multiplication and division, as well.

It could look like this then:

Random myRand = new Random();     
randomInteger = myRand.nextInt(4);

if (randomInteger == 0) {
  addition();
} else if (randomInteger == 1) {
  subtraction();
} else if (randomInteger == 2) {
  multiplication();
} else if (randomInteger == 3) {
  division();
}

Alternatively, a switch statement would be appropriate of course.

Upvotes: 1

Mureinik
Mureinik

Reputation: 311478

You could use java.util.Random#nextBoolean():

// should only be done once, in some initialization block
Random myRand = new Random();     

// Then, once you have your Random instance:
if (myRand.nextBoolean()) {
    addition();
} else {
    subtraction();
}

Upvotes: 5

Related Questions