Java原来如此随机数

在Java中,生成随机数有两种方法。1是使用Random类。2是使用Math类中的random方法。

我们现在做个例子,比如生成20个0到10之间的随机数。

1.使用Random类的nextInt(n)方法,n代表0到n之间,包括0,不包括n。

Random random = new Random();
for(int i=0;i<20;i++)
{
  System.out.println(random.nextInt(10));
}

2.使用Math类中的random方法,它生成的随机数是0.0到1.0之间的double。要生成int就需要类型转换。

for(int i=0;i<10;i++)
{
	double n = Math.random();
	n *= 10;
	int m = (int)n;
	System.out.println(m);
}

这个例子比较简单,只是生成int,如果要生成其他类型的数,请参考其他方法

原文地址:https://www.cnblogs.com/zyaizz/p/3440871.html