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();
}
create a list containing 1 to 6. then shuffle it using Collection.shuffle. Then you will get random unique number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With