[英]how to generate list of 5 random numbers between 20 and 100 in java
我想生成20至100之间的5个随机数的列表。这是我的代码
public class RandomNumbers {
public static void main(String[] args){
for(int i = 0; i < 5; i++){
System.out.println((int)(Math.random() * 10));
}
}
}
使用以下代码(生成[从0
到80
] + 20
=> [从20
到100
]):
public class RandomNumbers {
public static void main(String[] args){
for(int i = 0; i < 5; i++){
System.out.println((int)((Math.random() * 81) + 20));
}
}
}
将计算设为Math.random() * 81 + 20
这将生成5个随机数,介于20和100之间(含20和100)。
public class RandomNumbers {
public static void main(String[] args){
for(int i = 0; i < 5; i++){
System.out.println(20 + (int)(Math.random() * ((100 - 20) + 1)));
}
}
}
这曾经进口java.util.concurrent.ThreadLocalRandom;
for (int i = 0; i < 5; i++) {
System.out.println(ThreadLocalRandom.current().nextInt(20, 100 + 1));
}
令人高兴的是, 没有数字重复并且不需要预先考虑数学,这意味着更改max和min的值非常有效,并且不容易出错 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.