[英]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.基本上我想生成 1-10 之间的随机数,这些随机数被放入我的集合中。 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.问题是我的循环大小是从 0 到 9,它会生成随机数,但是一旦是 5 个数字,一次是 7 个数字,一次是 3 个数字,而不是 9 个数字。 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.我也在用while循环做同样的事情,它也做同样的事情。
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.因为 Set collections 不能有重复的属性,也就是说,当你生成数字时,如果随机数中生成相同的数字,你的 Set 只能持有唯一的数字。
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.首先,您的循环索引从 0 到 9,即十次迭代。
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 10 or about 0.036%. ÷ 10 10或约 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.