我想知道如何在两个给定值之间生成一个随机数。

我能够生成一个随机数与以下:

Random r = new Random();

for(int i = 0; i < a.length; i++){
    for(int j = 0; j < a[i].length; j++){
        a[i][j] = r.nextInt();
    }

}

但是,如何生成0到100(包括)之间的随机数呢?


当前回答

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

如果您需要生成多个值,那么只需使用 For循环

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

如果你想指定一个更合适的范围,比如从10到100(两者都在这个范围内)

所以代码是:

   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*/

其他回答

像这样,

Random random = new Random();
int randomNumber = random.nextInt(upperBound - lowerBound) + lowerBound;

你也可以试试下面的方法:

public class RandomInt { 
    public static void main(String[] args) { 

        int n1 = Integer.parseInt(args[0]);
        int n2 = Integer.parseInt(args[1]);
        double Random;

        if (n1 != n2)
        {
            if (n1 > n2)
            {
                Random = n2 + (Math.random() * (n1 - n2));
                System.out.println("Your random number is: " + Random);
            }
            else
            {
                Random = n1 + (Math.random() * (n2 - n1));   
                System.out.println("Your random number is: " +Random);
            }
        } else {
            System.out.println("Please provide valid Range " +n1+ " " +n2+ " are equal numbers." );
        }                     
    }
}

你可以用r.nextInt(101)

对于更通用的“在两个数字之间”使用:

Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;

这将为您提供一个介于10(包含)和100(不包含)之间的随机数

假设上界是上界,下界是下界,那么你可以在两个上界之间做一个随机数r:

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

使用Random.nextInt (int)。

在你的例子中,它看起来是这样的:

a[i][j] = r.nextInt(101);