获取随机数需要用到Math结构,Math为一个类,要用到类里边的Math.random()方法;
可以在API文档中找到:
Returns a
double
value with a positive sign, greater than or equal to0.0
and less than1.0
.返回值为double型的正数,数值范围为【0.0,1.0)
默认:double value = Math.random();//[0.0,1.0)
要想得到10~99之间的随机数,没有相应的方法实现,只能自己配,达到想要的类型和范围过程:
>Math.random()数值范围为【0.0,1.0),则value值范围也为数值范围为【0.0,1.0)。
>Math.random()*100数值范围为【0.0,100.0),则value值的范围为【0.0,100.0)不符合要求
>Math.random()*90数值范围为【0.0,90.0),则value值的范围为【0.0,90.0)。
为什么是*90?--->99-10+1=90刚好0+10=10,90+10=100;范围变为【10.0,100.0);若为其他范围同样计算
>Math.random()*90+10数值范围为【10.0,100.0)---------->[10.0,99.0];但是数据类型为double
使用强转符,将double型强制转换为int:(int)(Math.random()*90+10)定义一个int型变量进行赋值
int value = (int)(Math.random()*90+10);//随机数[10~100) 得到[10,99]
总结公式:要随机【a,b】之间的数值:int 变量名 = (int)(Math.random()*(b-a+1)+a)
double 变量名 = Math.random()*(b-a+1)+a
注:强转时不要忘记()