[英]How to generate 100 random 3 digit numbers in java?
我需要生成100个随机的3位数字。 我已经弄清楚了如何生成1个3位数字。 我如何产生100? 到目前为止,这就是我所拥有的...
import java.util.Random;
public class TheNumbers {
public static void main(String[] args) {
System.out.println("The following is a list of 100 random" +
" 3 digit numbers.");
Random rand= new Random();
int pick = rand.nextInt(900) + 100;
System.out.println(pick);
}
}
基本概念是使用for-next
循环,您可以在其中重复所需次数的计算...
您应该查看The for Statement以获得更多详细信息
Random rnd = new Random(System.currentTimeMillis());
for (int index = 0; index < 100; index++) {
System.out.println(rnd.nextInt(900) + 100);
}
现在,这不会排除生成重复项的可能性。 您可以使用Set
来确保值的唯一性...
Set<Integer> numbers = new HashSet<>(100);
while (numbers.size() < 100) {
numbers.add(rnd.nextInt(900) + 100);
}
for (Integer num : numbers) {
System.out.println(num);
}
尝试循环
for(int i=0;i<100;i++)
{
int pick = rand.nextInt(900) + 100;
System.out.println(pick);
}
如果您将以下代码适应您的问题
for(int i= 100 ; i < 1000 ; i++) {
System.out.println("This line is printed 900 times.");
}
,它将做您想要的。
使用问题的答案使用Java生成一定范围内的随机数 :
import java.util.Random;
public class TheNumbers {
public static void main(String[] args) {
System.out.println("The following is a list of 100 random 3 digit nums.");
Random rand = new Random();
for(int i = 1; i <= 100; i++) {
int randomNum = rand.nextInt((999 - 100) + 1) + 100;
System.out.println(randomNum);
}
}
如果3位数字包括以0开头的数字(例如,如果您正在生成PIN码),例如000、011、003等,则此解决方案是一种替代方法。
Set<String> codes = new HashSet<>(100);
Random rand = new Random();
while (codes.size() < 100)
{
StringBuilder code = new StringBuilder();
code.append(rand.nextInt(10));
code.append(rand.nextInt(10));
code.append(rand.nextInt(10));
codes.add(code.toString());
}
for (String code : codes)
{
System.out.println(code);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.