Java Generate Random Number Between Two Given Values

This question already has an answer here:

  • How do I generate random integers within a specific range in Java? 57 answers

  • You could use eg r.nextInt(101)

    For a more generic "in between two numbers" use:

    Random r = new Random();
    int Low = 10;
    int High = 100;
    int Result = r.nextInt(High-Low) + Low;
    

    This gives you a random number in between 10 (inclusive) and 100 (exclusive)


    假设上限是上限,下限是下限,则可以在两个边界之间使用随机数r:

    int r = (int) (Math.random() * (upper - lower)) + lower;
    

    Er...

    int Random = (int)(Math.random()*100);
    

    if You need to generate more than one value, then just use for loop for that

     for (int i = 1; i <= 10 ; i++)
           {
            int Random = (int)(Math.random()*100);
            System.out.println(Random);
           }
    

    If You want to specify a more decent range, like from 10 to 100 ( both are in the range )

    so the code would be :

       int Random =10 +  (int)(Math.random()*(91));
       /* int Random = (min.value ) + (int)(Math.random()* ( Max - Min + 1));
      *Where min is the smallest value You want to be the smallest number possible to       
      generate and Max is the biggest possible number to generate*/
    
    链接地址: http://www.djcxy.com/p/17654.html

    上一篇: 生成1到10个Java之间的随机数

    下一篇: Java在两个给定值之间生成随机数