1. 程式人生 > >JAVA產生指定範圍的隨機整數

JAVA產生指定範圍的隨機整數

1、方法一Math.random()

int num = min + (int)(Math.random() * (max-min+1));
public class Merge_array{
    public static void main(String[] args){
        int min=5;
        int max=10;
        int[] arr=new int[50];
        for(int i=0;i<50;i++){
            arr[i]=min+(int)(Math.random()*(max-min+1
)); } for(int i=0;i<50;i++){ System.out.print(arr[i]+" "); } } }

因為使用了強制轉換型別,所以是max-min+1

2、方法二java.util.Random

Random 是 java 提供的一個偽隨機數生成器。

import java.util.Random;

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param
min Minimum value * @param max Maximum value. Must be greater than min. * @return Integer between min and max, inclusive. * @see java.util.Random#nextInt(int) */
public static int randInt(int min, int max) { // NOTE: Usually this should be a field rather than a method // variable so that it is not re-seeded every call.
Random rand = new Random(); // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randomNum = rand.nextInt((max - min) + 1) + min; return randomNum; }

方法二和方法一類似,只不過一個是Math庫中的,一個是util中的。

3、標準庫

org.apache.commons.lang3.RandomUtils 提供瞭如下產生指定範圍的隨機數方法:

// 產生 start <= 隨機數 < end 的隨機整數
public static int nextInt(final int startInclusive, final int endExclusive);

// 產生 start <= 隨機數 < end 的隨機長整數
public static long nextLong(final long startInclusive, final long endExclusive);

// 產生 start <= 隨機數 < end 的隨機雙精度數
public static double nextDouble(final double startInclusive, final double endInclusive);

// 產生 start <= 隨機數 < end 的隨機浮點數
public static float nextFloat(final float startInclusive, final float endInclusive);