Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate 6 random numbers between 1 and 6 using Java?

I am encountering a problem generating 6 random numbers between 1 and 6 in Java. All the numbers have to be unique. When I enter kolon value 5, the arrays should be like this:

1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6

I don't want the program to generate the same two numbers. What is wrong here?

Relevant code:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter row quantity: ");

    int kolon = input.nextInt();

    Integer[][] dizi_asil = new Integer[kolon][6];

    for (int i = 0; i < kolon; i++) {
        Integer[] dizi = new Integer[6];

        for (int j = 0; j < 6; j++) { 

            dizi[j] = (int) ((Math.random() * 6) + 1);  

            for (int u = 0; u < 1; u++) { 

                for (int k = 0; k < j; k++) { 

                    while (dizi[k] == dizi[j]) { 
                        dizi[j] = (int) ((Math.random()* 6)  + 1);
                        u++;
                    }

                }
            }
            dizi_asil[i][j] = dizi[j];
        }
        Arrays.sort(dizi_asil[i]);
    }

    for (int i = 0; i < dizi_asil.length; i++) {
        for (int k = 0; k < dizi_asil[i].length; k++) {
            System.out.print(dizi_asil[i][k] + "\t");
        }
        System.out.println();
    }
like image 735
Ertuğrul Çetin Avatar asked Nov 30 '22 01:11

Ertuğrul Çetin


1 Answers

create a list containing 1 to 6. then shuffle it using Collection.shuffle. Then you will get random unique number

like image 68
stinepike Avatar answered Jan 26 '23 00:01

stinepike