4

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!!

yolam
  • 59
  • 1
  • 6

3 Answers3

9

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;
}
Bubletan
  • 3,693
  • 6
  • 23
  • 33
3

You can just use Set. Set will ensure that there will be 6 different numbers.

public static void main(String[] args) {
    Random random = new Random();
    Set<Integer> numbers = new HashSet<>(6);

    while (numbers.size() < 6) {
        numbers.add(1 + random.nextInt(10));
    }

    System.out.println(numbers);
}
Aleksander Mielczarek
  • 2,577
  • 1
  • 20
  • 39
0

You can do something like that:

public static int randInt(int min, int max) {

    Random rand = new Random();

    int randomNum = rand.nextInt((max - min) + 1) + min;

   return randomNum;
}

Source: How do I generate random integers within a specific range in Java?

Community
  • 1
  • 1
NDY
  • 3,319
  • 4
  • 43
  • 62