java 生成[min,max]之间的随机整数 caomiao2006的专栏 的博客:Java获取随机数的3种方法

这里使用Random类的nextInt()方法来生成,生成[min,max]区间的随机整数公式

Random rand=new Random();

rand.nextInt(max- min+ 1) + min;

这里封装成方法了:

/**
 * 求[Min,Max]区间之间的随机整数。
 * @param Min 最小值
 * @param Max 最大值
 * @return 一个Min和Max之间的随机整数
 */
public static int randomIntMinToMax(int Min, int Max)
{
	//如果相等,直接返回,还生成个屁
	if(Min==Max)
	{
		return Max;
	}
	//如果Min比Max大,交换两个的值,如果不交换下面nextInt()会出错
	if(Min>Max)
	{
		Min^=Max;
		Max^=Min;
		Min^=Max;
	}
	Random rand=new Random();//nextInt()不是静态方法,不能直接用类名调用
	return rand.nextInt(Max - Min + 1) + Min;
}

实例:

package random;

import java.util.Random;

public class GetRandom
{
    public static void main(String[] args)
    {
        Random rand = new Random();
        int Min = 0;
        int Max = 9;
        int[] count = new int[Max - Min + 1];
        for (int i = 0; i < 10000; i++)
        {
            count[randomIntMinToMax(Min, Max)]++;
        }
        System.out.println();
        char percentCh = '%';
        for (int i = 0; i < count.length; i++)
        {
            double percent = 100 * (double) count[i] / 10000;
            System.out.printf("%d生成次数:%-4d,占百分比:%.2f%c\n", i, count[i], percent,
                    percentCh);
        }
    }
    /**
     * 求[Min,Max]区间之间的随机整数。
     * 
     * @param Min
     *            最小值
     * @param Max
     *            最大值
     * @return 一个Min和Max之间的随机整数
     */
    public static int randomIntMinToMax(int Min, int Max)
    {
        // 如果相等,直接返回,还生成个屁
        if (Min == Max)
        {
            return Max;
        }
        // 如果Min比Max大,交换两个的值,如果不交换下面nextInt()会出错
        if (Min > Max)
        {
            Min ^= Max;
            Max ^= Min;
            Min ^= Max;
        }
        Random rand = new Random();// nextInt()不是静态方法,不能直接用类名调用
        return rand.nextInt(Max - Min + 1) + Min;
    }
}

运行结果:

0生成次数:998 ,占百分比:9.98%
1生成次数:962 ,占百分比:9.62%
2生成次数:1005,占百分比:10.05%
3生成次数:1020,占百分比:10.20%
4生成次数:1020,占百分比:10.20%
5生成次数:997 ,占百分比:9.97%
6生成次数:966 ,占百分比:9.66%
7生成次数:1002,占百分比:10.02%
8生成次数:1006,占百分比:10.06%
9生成次数:1024,占百分比:10.24%

参考博客:


猜你喜欢

转载自blog.csdn.net/qq_21808961/article/details/80526231