繁体   English   中英

如何在Java中生成20至100之间的5个随机数的列表

[英]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));
        }
    }
}

使用以下代码(生成[从080 ] + 20 => [从20100 ]):

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.

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