简体   繁体   中英

Size of the loop is printing less numbers than i want to be in my Set JAVA

Basically i want to generate random numbers between 1-10, which are put into my set. The thing is that my loop size is from 0 to 9 and it generates random numbers but, once it's 5 numbers, once 7 numbers, once 3 numbers and not exactly 9 numbers. Why?

private static Set<Integer> losowanie() {
   
    Set<Integer> result = new TreeSet<>();
    Random random = new Random();

    for (int i = 0; i < 10; i++){
        result.add(random.nextInt(10) + 1);
    }
    return result;

    }
}

also i was doing the same thing with while loop and it does the same.

Because Set collections cannot have duplicate properties, that is, when you generate numbers, if the same number is generated in the random number, your Set can only hold a unique number.

public static void main(String[] args) {
        Set<Integer> result=new TreeSet<>();
        for (int i = 0; i < 10; i++) {
            result.add(1);
        }
        //only one data: [1]
        System.out.println(result);
        result=new TreeSet<>();
        for (int i = 0; i <10 ; i++) {
            result.add(i);
        }
        //ten data:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        System.out.println(result);

    }

First of all, your loop indexes from 0 to 9, and that's ten iterations.

So, you might expect ten numbers in your set. But set elements have to be unique, and you are inserting elements randomly selected from a set of only ten possibilities.

The chances of that happening are 10! ÷ 10 10 or about 0.036%. Keep running your program.

If your goal is to have ten different numbers in a random order, do this instead:

List<Integer> result = IntStream.rangeClosed(1, 10)
    .boxed()
    .collect(Collectors.toList());
Collections.shuffle(random);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM