使用Java

时间:2015-10-07 13:59:00

标签: java random int

我能够在我的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); 
    }    
}

4 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:2)

要从1-49获得随机数,您应该选择0-48之间的随机数,然后加1:

int min=1;
int max=49;

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

答案 2 :(得分:1)

你可以使用略有不同的随机化习语:

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

答案 3 :(得分:0)

尝试使用util包中的Random类:

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