如何在java中生成100个随机的3位数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18523526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate 100 random 3 digit numbers in java?
提问by Chris
I need to generate 100 random 3 digit numbers. I have figured out how to generate 1 3 digit number. How do I generate 100? Here's what I have so far...
我需要生成 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);
}
}
}
回答by newuser
回答by Mario Rossi
If you adapt the following piece of code to your problem
如果您将以下代码调整到您的问题
for(int i= 100 ; i < 1000 ; i++) {
System.out.println("This line is printed 900 times.");
}
, it will do what you want.
,它会做你想做的。
回答by eKek0
Using the answer to the question Generating random numbers in a range with Java:
使用问题在 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);
}
}
回答by MadProgrammer
The basic concept is to use a for-next
loop, in which you can repeat your calculation the required number of times...
基本概念是使用for-next
循环,您可以在其中重复计算所需的次数...
You should take a look at The for Statementfor more details
您应该查看The for Statement以获取更多详细信息
Random rnd = new Random(System.currentTimeMillis());
for (int index = 0; index < 100; index++) {
System.out.println(rnd.nextInt(900) + 100);
}
Now, this won't preclude generating duplicates. You could use a Set
to ensure the uniqueness of the values...
现在,这不会排除生成重复项。您可以使用 aSet
来确保值的唯一性...
Set<Integer> numbers = new HashSet<>(100);
while (numbers.size() < 100) {
numbers.add(rnd.nextInt(900) + 100);
}
for (Integer num : numbers) {
System.out.println(num);
}
回答by jbx
This solution is an alternative if the 3-digit numbers include numbers that start with 0 (if for example you are generating PIN codes), such as 000, 011, 003 etc.
如果 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);
}