取随机数
- random方法只能生成小于1的随机小数(包括0和正小数),并不能生成随机整数。
- Random随机数工具包,可以解决random方法的问题:
import java.util.Random;
该工具实例化(new)后,nextInt 方法生成int类型的随机整数、nextLong 方法生成long类型的随机长整数、nextfloat 方法生成float类型的随机浮点小数、nextdouble 方法生成double类型的随机双精度小数。
(注:nextInt 和 nextLong 方法得到的随机整数可能是负数,而其他两个只能是正小数)
接下来就详细讲解Random中的nextInt,其他的都跟其一样。
Java Random.next***()
语法
int nextInt() //随机返回一个int型整数
int nextInt(int num) //随机返回一个值在[0,num)的int类型的整数,包括0不包括num
实例
/**
* 生成任意整数
*/
@Test
public void RandomNextIntDemo1(){
Random r = new Random();
int