【问题标题】:Generate a random number between a desired range using Java [duplicate]使用Java在所需范围之间生成一个随机数[重复]
【发布时间】:2015-10-07 13:58:59
【问题描述】:

我能够在我的 java 代码中生成一个介于 [0,50] 之间的随机数,但我该如何继续以创建例如 [1,49] 范围内的数字

这是我的代码:

public class Totoloto 
{
    public static void main(String[] args) 
    {
        int n = (int) (Math.random()*50);
        System.out.println("Number generated: "+n); 
    }    
}

【问题讨论】:

    标签: java random int


    【解决方案1】:

    要得到一个1-49的随机数,你应该选择一个0-48之间的随机数,然后加1:

    int min=1;
    int max=49;
    
    Random random=new Random();
    int randomnumber=random.nextInt(max-min)+min;
    

    【讨论】:

    • 不应该是random.nextInt(max-min)+min吗!
    • 是的,我的错,对不起,这是一个错字:)
    【解决方案2】:

    利用Random 类。如果您有一个设计为generateRandom(int min, int max) 的方法,那么您可以像这样创建它

    private static Random r = new Random();
    
    public static void main(String[] args) {
        for(int i = 0;i<10; ++i)
            System.out.println(generateRandom(-1,1));
    }
    
    
    private static int generateRandom(int min, int max) {
        // max - min + 1 will create a number in the range of min and max, including max. If you don´t want to include it, just delete the +1.
        // adding min to it will finally create the number in the range between min and max
        return r.nextInt(max-min+1) + min;
    }
    

    【讨论】:

    • 这实际上并没有优化,因为您每次调用都初始化一个新的Random
    • 在每次调用中创建新的 Random 真的很糟糕吗! Random对象返回到被调用方法后,GC不会自动删除!!!
    【解决方案3】:

    您可以使用稍微不同的随机化习语:

    Random r = new Random();
    while (true) {
        // lower bound is 0 inclusive, upper bound is 49 exclusive
        // so we add 1
        int n = r.nextInt(49) + 1;
        System.out.println("Number generated: "+n); 
    }
    

    将打印 1 到 49 之间的无限随机数列表。

    等效的 Java 8 习语:

    r.ints(0, 49).forEach((i) -> {System.out.println(i + 1);});
    

    【讨论】:

    • 但是这条线是如何工作的? int n= r.nextInt(50) +1;通过添加 1,如何将范围转换为 [1,49]?
    • @Gazelle 错字我这边,它是 49 - 已修复。现在上限是 49,所以随机 int 介于 0 和 48 之间。您总是加 1,所以它在 1 到 49 之间。
    【解决方案4】:

    尝试使用 util 包中的 Random 类:

    Random r = new Random();
    int n = r.nextInt(49) + 1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-15
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-01
      • 2013-07-13
      相关资源
      最近更新 更多