📌  相关文章
📜  如何在Java中生成特定范围内的随机整数?

📅  最后修改于: 2022-05-13 01:54:37.023000             🧑  作者: Mango

如何在Java中生成特定范围内的随机整数?

给定两个数字MinMax ,任务是在Java中生成这个特定范围内的随机整数。

例子:

Input: Min = 1, Max = 100
Output: 89

Input: Min = 100, Max = 899
Output: 514

方法:

  • 获取指定范围的最小值和最大值。
  • 调用ThreadLocalRandom 类(Java.util.concurrent.ThreadLocalRandom ) 的 nextInt() 方法,并将 Min 和 Max 值作为参数指定为
    ThreadLocalRandom.current().nextInt(min, max + 1);
  • 返回接收到的随机值
// Java program to generate a random integer
// within this specific range
  
import java.util.concurrent.ThreadLocalRandom;
  
class GFG {
  
    public static int getRandomValue(int Min, int Max)
    {
  
        // Get and return the random integer
        // within Min and Max
        return ThreadLocalRandom
            .current()
            .nextInt(Min, Max + 1);
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        int Min = 1, Max = 100;
  
        System.out.println("Random value between "
                           + Min + " and " + Max + ": "
                           + getRandomValue(Min, Max));
    }
}
输出:
Random value between 1 and 100: 35