Java中Math类的random()方法可以生成[0,1)之间的随机浮点数。而double类型数据强制转换成int类型,整数部分赋值给int类型变量,小数点之后的小数部分将会丢失。
如果要生成[0,n]的随机整数的话,只需要Math.random()乘以n+1,生成[0,n+1)的浮点数,再强制类型转换为int类型,只取其整数部分,即可得到[0,n]的整数。
int b=(int)(Math.random()*10);//生成[0,9]之间的随机整数。
int temp=m+(int)(Math.random()*(n+1-m)); //生成从m到n的随机整数[m,n]
测试每个生成的随机数的概率:
public class TestMath
{
public static void main(String[] args)
{
int[] count=new int[10];
int base=1000000000;
int b;
for(int i=0;i 9)
{
break;
}
switch (b)
{
case 0:
count[0]++;
break;
case 1:
count[1]++;
break;
case 2:
count[2]++;
break;
case 3:
count[3]++;
break;
case 4:
count[4]++;
break;
case 5:
count[5]++;
break;
case 6:
count[6]++;
break;
case 7:
count[7]++;
break;
case 8:
count[8]++;
break;
case 9:
count[9]++;
break;
}
}
for(int i=0;i<10;i++)
{
double eachPercent= ((double)count[i]/base)*100;
System.out.println(i+": "+eachPercent+"%"+",");
}
}
}
运行结果:
0: 10.0005311%,
1: 10.0011356%,
2: 10.000164%,
3: 9.9996706%,
4: 9.999522800000001%,
5: 10.0005772%,
6: 10.0003636%,
7: 9.99965%,
8: 9.9987534%,
9: 9.9996317%,
可以看到这10个数生成的概率基本都是一致的,每个占10%。
使用Random类生成从n到m的随机整数:
import java.util.Random;
public class RandomTest
{
public static void main(String[] args)
{
int max = 20;
int min = 10;
Random random = new Random();
int s = random.nextInt(max) % (max - min + 1) + min;
System.out.println(s);
}
}
random.nextInt(m)表示生成[0,m-1]之间的随机数,也就是说random.nextInt(m+1),将生成[0,m]之间的随机整数。
测试每个生成的随机数概率
import java.util.Random;
public class RandomTest
{
public static void main(String[] args)
{
int min = 0;
int max = 9;
Random random = new Random();
//random.nextInt(max+1)表示生成[0,max]之间的随机数
int[] count=new int[10];
int base=10000000;
int b;
for(int i=0;i 9)
{
break;
}
switch (b)
{
case 0:
count[0]++;
break;
case 1:
count[1]++;
break;
case 2:
count[2]++;
break;
case 3:
count[3]++;
break;
case 4:
count[4]++;
break;
case 5:
count[5]++;
break;
case 6:
count[6]++;
break;
case 7:
count[7]++;
break;
case 8:
count[8]++;
break;
case 9:
count[9]++;
break;
}
// System.out.println(b);
}
for(int i=0;i<10;i++)
{
double eachPercent= ((double)count[i]/base)*100;
System.out.println(i+": "+eachPercent+"%"+",");
}
}
}
结果:
0: 10.01158%,
1: 9.99082%,
2: 10.0109%,
3: 10.00464%,
4: 9.99602%,
5: 9.991990000000001%,
6: 9.995560000000001%,
7: 9.998990000000001%,
8: 9.98683%,
9: 10.01267%,
可以看到生成的[m,n]之间的随机整数的方法:先生成[0,n-m]的随机整数,然后再加上m,即可得到[m,n]之间的随机整数。