I wrote down my code at first and then it cannot ensure that it is 6 different number.
public class JavaTest{
public static void main(String[] args){
int[] list = new int[6];
int number = (int)(Math.random() * 10 + 1);
for (int i = 0; i < list.length; i++){
list[i] = number;
number = (int)(Math.random() * 10 + 1);
for (int j = 1; j < i; j++){
number = (int)(Math.random() * 10 + 1);
if (number == list[j])
number = (int)(Math.random() * 10 + 1);
}
}
for (int i = 0; i < list.length; i++){
System.out.print(list[i] + " ");
}
}
}
I think something wrong with my inner for loop j, but I don't know how to improve it. Can anyone help me modify it? Thanks a lot!!
You could possibly do something like:
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Collections.shuffle(list);
And then take the 6 first numbers.
Without using collections:
int[] list = new int[6];
boolean[] used = new boolean[10];
for (int i = 0; i < 6; i++) {
int number = (int) ((10 - i) * Math.random());
for (int a = 0; a <= number; a++) {
if (used[a]) {
number++;
}
}
list[i] = number + 1;
used[number] = true;
}
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