zyaizz

在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,如果要生成其他类型的数,请参考其他方法

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-16
  • 2021-11-30
  • 2022-01-06
  • 2021-11-05
  • 2022-01-24
猜你喜欢
  • 2022-12-23
  • 2021-08-18
  • 2021-07-25
  • 2022-12-23
  • 2022-02-02
  • 2022-12-23
相关资源
相似解决方案