在许多编程项目中,随机数都是一个必不可少的部分。在Java中,我们可以通过 Random
类生成随机数。而其中,random.next
方法是其中最常使用的方法之一。本文将从多个方面介绍 random.next
的详细信息。
一、random.next 随机数范围
public int nextInt(int bound)
在使用 nextInt
方法时,需要注意一个参数——bound
。这个参数决定了 nextInt
返回整数的范围。如果不指定 bound
参数,则默认返回 32 位整数的范围。
我们可以通过以下代码来了解 nextInt
方法的随机数范围:
Random random = new Random();
System.out.println(random.nextInt(100));
System.out.println(random.nextInt(100));
System.out.println(random.nextInt());
System.out.println(random.nextInt());
这个例子中,我们首先指定了 bound
参数为 100,前两个 nextInt
方法就会返回 0 到 99 之间的随机整数。后两个 nextInt
方法没有指定 bound
参数,因此返回 32 位整数的范围。
二、random.nextInt 默认
public int nextInt()
如果不需要指定范围,可以使用 nextInt()
方法,这样就会返回 32 位整数的范围内的随机整数,如下所示:
Random random = new Random();
System.out.println(random.nextInt());
System.out.println(random.nextInt());
System.out.println(random.nextInt());
System.out.println(random.nextInt());
三、random.next 返回字符
public double nextDouble()
除了生成随机整数之外,我们还可以使用 nextDouble
方法生成随机的浮点数。这个方法返回 0.0
(含)和 1.0
(不含)之间的随机 double
类型的值。
下面是证明:
Random random = new Random();
System.out.println(random.nextDouble());
System.out.println(random.nextDouble());
System.out.println(random.nextDouble());
System.out.println(random.nextDouble());
四、random.nextInt 不填参数选取
public int nextInt()
如果不传递参数,nextInt
方法默认是返回 32 位整数的范围内的随机整数,如下所示:
Random random = new Random();
System.out.println(random.nextInt());
System.out.println(random.nextInt());
System.out.println(random.nextInt());
System.out.println(random.nextInt());
此外,我们还可以使用 nextBoolean
方法生成随机的布尔值,如下所示:
Random random = new Random();
System.out.println(random.nextBoolean());
System.out.println(random.nextBoolean());
System.out.println(random.nextBoolean());
System.out.println(random.nextBoolean());
五、总结
本文从多个角度介绍了 Java 中 Random
类的 random.next
方法。我们可以使用 nextInt
方法和 nextDouble
方法生成随机的整数和浮点数,通过传递 bound
参数可以控制生成的范围;同时,也可以使用 nextInt()
方法生成 32 位整数的范围内的随机整数和 nextBoolean
方法生成随机的布尔值。这些方法的使用可以帮助我们解决很多编程项目中需要使用随机数的问题。