简体   繁体   English

如何在Java中生成100个随机的3位数字?

[英]How to generate 100 random 3 digit numbers in java?

I need to generate 100 random 3 digit numbers. 我需要生成100个随机的3位数字。 I have figured out how to generate 1 3 digit number. 我已经弄清楚了如何生成1个3位数字。 How do I generate 100? 我如何产生100? Here's what I have so far... 到目前为止,这就是我所拥有的...

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);


}

} }

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 Statement for 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... 您可以使用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);
}

Try for loop 尝试循环

for(int i=0;i<100;i++)
      {
          int pick = rand.nextInt(900) + 100;
          System.out.println(pick);
      }

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. ,它将做您想要的。

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);
      }
}

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM