Learningmind
Learningmind

Reputation: 127

if statement or loop

I am trying to figure out if I need to use if statement or loop in my code. If random2 equals random1 then I want the random2 to generate another random number. If second time around random2 is again equal to random1, I want the code to keep running until it generates a different number from random1. Some guidance would be much appreciated.

public void generate(View view) {
        Random randomGenerator = new Random();
        int random1 = randomGenerator.nextInt(10);
        int random2 = randomGenerator.nextInt(10);

Upvotes: 0

Views: 51

Answers (2)

Suppen
Suppen

Reputation: 856

I would go for a loop:

Random rng = new Random();

int r1 = rng.nextInt(10);
int r2;

do {
    r2 = rng.nextInt(10);
while (r1 == r2);

Upvotes: 0

Guffa
Guffa

Reputation: 700382

You should use a loop. Create a new random number until they differ:

Random randomGenerator = new Random();
int random1 = randomGenerator.nextInt(10);
int random2;
do {
  random2 = randomGenerator.nextInt(10);
} while(random1 == random2);

Upvotes: 2

Related Questions