如何在 Java 中生成一个 1 到 10 之间的随机数

Rupam Yadav 2023年10月12日
  1. random.nextInt() 生成 1 和 10 之间的随机数
  2. Math.random() 生成 1 到 10 之间的随机数
  3. ThreadLocalRandom.current.nextInt() 生成 1 到 10 之间的随机数
如何在 Java 中生成一个 1 到 10 之间的随机数

我们将看看在 Java 中随机生成 1 到 10 之间的随机数的步骤。我们将看到三个可以生成 1 到 10 之间随机数的 Java 包或类,以及其中哪个是最适合使用的。

random.nextInt() 生成 1 和 10 之间的随机数

java.util.Random 是 Java 自带的一个包,我们可以用它来生成一个范围之间的随机数。在我们的例子中,范围是 1 到 10。

这个包有一个类 Random,它允许我们生成多种类型的数字,无论是 int 还是 float. 检查一下这个例子,以便更好地理解。

import java.util.Random;

public class Main {
  public static void main(String[] args) {
    int min = 1;
    int max = 10;

    Random random = new Random();

    int value = random.nextInt(max + min) + min;
    System.out.println(value);
  }
}

输出:

	6

为了证明上面的技术是有效的,并且每次都能生成随机数,我们可以使用一个循环来生成一个新的随机数,直到它完成。由于我们的数字范围不大,随机数可能会被重复。

import java.util.Random;

public class Main {
  public static void main(String[] args) {
    Random random = new Random();

    for (int i = 1; i <= 10; i++) {
      int value = random.nextInt((10 - 1) + 1) + 1;
      System.out.println(value);
    }
  }

输出:

10
7
2
9
2
7
6
4
9

Math.random() 生成 1 到 10 之间的随机数

另一个可以帮助我们实现目标的类是 Math,它有多个静态函数来随机化数字。我们将使用 random() 方法。它返回一个 float 类型的随机值。这就是为什么我们要把它转换为一个 int

public class Main {
  public static void main(String[] args) {
    int min = 1;
    int max = 10;
    for (int i = min; i <= max; i++) {
      int getRandomValue = (int) (Math.random() * (max - min)) + min;
      System.out.println(getRandomValue);
    }
  }

输出:

5
5
2
1
6
9
3
6
5
7

ThreadLocalRandom.current.nextInt() 生成 1 到 10 之间的随机数

我们列表中最后一个获取 1 到 10 之间随机数的方法是使用 JDK 7 中为多线程程序引入的 ThreadLocalRandom 类。

下面我们可以看到,我们必须调用该类的 current() 方法,因为我们希望在当前线程中生成随机数。

import java.util.concurrent.ThreadLocalRandom;

public class Main {
  public static void main(String[] args) {
    int min = 1;
    int max = 10;

    for (int i = 1; i <= 10; i++) {
      int getRandomValue = ThreadLocalRandom.current().nextInt(min, max) + min;

      System.out.println(getRandomValue);
    }
  }
}

输出:

3
4
5
8
6
2
6
10
6
2
作者: Rupam Yadav
Rupam Yadav avatar Rupam Yadav avatar

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

LinkedIn

相关文章 - Java Number