使用java时,想要生成随机数,可以通过以下两种方法:
1.使用Random类,该类位于java.util.Random包下,包含nextInt(),nextInt(int a)和nextDouble()等多种
方法,该类的实例用于生成伪随机数的流。
2.使用math.random()方法,该方法位于java.lang.Math包下,用来生成一个伪随机数,返回值为0到1之
间的double类型的值。
下面为代码,可以自己动手敲一敲,这样会有更深的理解~
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
//The first method:采用random类随机生成在int范围内的随机数
Random rd=new Random(); //实例化一个Random对象,才可以使用这个类包含的成员方法
System.out.println(rd.nextInt());
System.out.println(rd.nextInt(100));
System.out.println(rd.nextLong());
System.out.println(rd.nextDouble());
System.out.println("==============");
//The second method:使用Math.random()生成一个范围内的随机数
//Math.random()默认生成0到1之间的小数
//当我想要生成一个0到10之间的随机数时......
System.out.println(Math.random()*10);
System.out.println(Math.round(Math.random()*10));
System.out.println("==============");
//Math.round()四舍五入函数
//Math.round(double a) 返回参数中最接近的long,其中 long四舍五入为正无穷大
//Math.round(float a) 返回参数中最接近的 int ,其中 int四舍五入为正无穷大
//JDK 8 新增的方法
rd.ints();//返回无限个int类型范围内的数据
int[] arr=rd.ints(10).toArray(); //生成10个int范围内的随机数
for(int i=0;i<arr.length;i++) {
System.out.println(arr[i]);
}
}
}