Random distinct numbers in nested loop

Sukonbu :

I am have enrolled in java course and completed nested loops but I was trying to play around with it and wanted to make columns of distinct random numbers but it prints 1 number to all columns. How can I make it so it prints random number to every slot (numbers can be repeated but not copied like its now)

    Random rng = new Random();
    int chance = rng.nextInt((100)+1);
    for (int row = 0; row < 5; row ++) {
        System.out.print("row " + row + ": ");
        for (int col = 0; col < 10; col++) {
            System.out.print(chance + " ");
        }
        System.out.println();
    }

This is the result:

row 0: 13 13 13 13 13 13 13 13 13 13

row 1: 13 13 13 13 13 13 13 13 13 13

row 2: 13 13 13 13 13 13 13 13 13 13

row 3: 13 13 13 13 13 13 13 13 13 13

row 4: 13 13 13 13 13 13 13 13 13 13

but what I need is every number to be randomly generated and not just roll 1 number and put it everywhere.

GhostCat salutes Monica C. :

Simple:

int chance = rng.nextInt((100)+1);

That line gets you a new random number and assigns it to your local variable.

Your code executes the above statement once, prior to the for loop. And then your loop prints what you put into that local variable.

If you want it to happen that "get me a random number" repeatedly, consider moving it into your loop.

That is all there is to this.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=131306&siteId=1