AndoTwo
AndoTwo

Reputation: 39

Looping with a random number generator in Java

I have a random number generator here that picks a number from 1 - 50.

What I want it to do is pick a second random number from 1-50, that will only print to the console if it is greater than the previous random number, and repeat a number of times, let's say 10 times.

My teacher wants me to use only the Math.floor(Math.random() method to generate a number so I have to work with that.

I'm not sure how to compare the latest generated number to the previous generated number.

What I got so far is

int myRand = 10;
    while (myRand > 0) {
        int myRand2 = (int) (Math.floor(Math.random() * 50) + 1);
        System.out.println(myRand2);
        System.out.println();
        myRand--;

Where would the second part that would compare that first generated number to subsequent generated numbers go?

Upvotes: 0

Views: 3249

Answers (2)

JB Nizet
JB Nizet

Reputation: 691625

Let's start by picking a random number:

int randomNumber = pick();

Now you need to pick another one

int otherRandomNumber = pick();

and print it to the console if it's bigger than the previous one

if (otherRandomNumber > randomNumber) {
    System.out.println(otherRandomNumber);
}

But you need to do that 10 times, so you need a loop:

for (int i = 0; i < 10; i++) {

And, at the end of each iteration, the "other", latest random number becomes the previous one of the next iteration, so let's rename variables and assemble all this:

int previousRandomNumber = pick();

for (int i = 0; i < 10; i++) {
    int otherRandomNumber = pick();

    if (otherRandomNumber > previousRandomNumber) {
        System.out.println(otherRandomNumber);
    }

    previousRandomNumber = otherRandomNumber;
}

Upvotes: 1

Peter
Peter

Reputation: 508

Your first variable myRand is not random... To me it looks more like your loop iterator. You are never making two random variables. If I understand your question correctly, your answer should look more like this:

int i = 10;
while (i > 0)
{
    int myRand1 = (int) (Math.floor(Math.random() * 50) + 1);
    int myRand2 = (int) (Math.floor(Math.random() * 50) + 1);
    if (myRand2 > myRand1)
        System.out.println(myRand2);

    System.out.println();
    i--;
}

Upvotes: 0

Related Questions