[英]how to generate list of 5 random numbers between 20 and 100 in java
i want to generate list of 5 random numbers between 20 and 100.Here is my code 我想生成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));
}
}
}
Use this code (generates [from 0
to 80
] + 20
=> [from 20
to 100
]): 使用以下代码(生成[从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
This will generate 5 random numbers between 20 and 100 inclusive. 这将生成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)));
}
}
}
This used import java.util.concurrent.ThreadLocalRandom ; 这曾经进口java.util.concurrent.ThreadLocalRandom;
for (int i = 0; i < 5; i++) {
System.out.println(ThreadLocalRandom.current().nextInt(20, 100 + 1));
}
The nice thing is there is no number repetition and no need for prethought out math, which means changing values for max and min is incredibly efficient and less prone to error . 令人高兴的是, 没有数字重复并且不需要预先考虑数学,这意味着更改max和min的值非常有效,并且不容易出错 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.