Adriann Adriann - 27 days ago 11
Java Question

Random Generator always generates number 0

I would like to know why the first number generated is always "0".

Here is the code:

public static void main(String[] args) {

boolean[] pack = new boolean[52];
int[] cards = new int[5];

for (int i = 0; i < pack.length - 1; i++) {
System.out.print(pack[i] + " | ");
}
System.out.println();

Random give = new Random();

for (int i = 0; i < cards.length; i++) {
while (pack[cards[i]])
cards[i] = give.nextInt(5);

pack[cards[i]] = true;
System.out.println(cards[i]);

}

for (int i = 0; i < pack.length - 1; i++) {
System.out.print(pack[i] + " | ");
}
}

Answer

Because pack(cards[i]) is always false on the first iteration. The solution could be implementing a do-while instead a while.

Check this:

Main:

import java.util.Random;
public class hw {

       public static void main(String[] args) {

            boolean[] pack = new boolean[52];
            int[] cards = new int[5];

            for (int i = 0; i < pack.length - 1; i++) 
            {
                System.out.print(pack[i] + " | ");         
            }

            System.out.println();

            Random give = new Random();

            for (int i = 0; i < cards.length; i++) {
                do
                {
                    cards[i] = give.nextInt(5); 
                }
                while ( pack[cards[i]] );

                pack[cards[i]] = true;                 
                System.out.println(cards[i]);
            }

            for (int i = 0; i < pack.length - 1; i++) 
            {
                System.out.print(pack[i] + " | ");         
            }     
       }

}

Output:

false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false |

4

3

0

1

2

true | true | true | true | true | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false | false |

Comments