我想知道如何在两个给定值之间生成一个随机数。
我能够用以下方法生成一个随机数。
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 (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*/