Java基础知识强化82:Random类概述和方法使用

1. Random类

1 public class Random  extends  Object implements  Serializable;

此类的实例用于生成伪随机数流。此类使用48位种子。

(1)Random类概述

• 此类用于产生随机数

• 如果用相同的种子创建两个Random实例,则对每个实例进行相同的方法调用序列,它们将生成并返回相同的数字序列。

(2)Random的构造方法

•  public Random():没有给种子,用的就是默认种子,是当前时间的毫秒值

•  public Random(long  seed):给固定的种子seed

种子:一般计算机的随机数都是伪随机数,以一个真随机数(种子)作为初始条件,然后用一定的算法不停迭代产生随机数。

(3)Random成员方法

1 public  int  nextInt():            返回是int范围内的随机数
2 public  int  nextInt(int n ):      返回的是[0,n)范围内的随机数

(4)代码示例:

 1 package cn.itcast_01;
 2 
 3 import java.util.Random;
 4 
 5 /*
 6  * Random:产生随机数的类
 7  * 
 8  * 构造方法:
 9  *         public Random():没有给种子,用的是默认种子,是当前时间的毫秒值
10  *        public Random(long seed):给出指定的种子
11  *
12  *        给定种子后,每次得到的随机数是相同的。
13  *
14  * 成员方法:
15  *         public int nextInt():返回的是int范围内的随机数
16  *        public int nextInt(int n):返回的是[0,n)范围的内随机数
17  */
18 public class RandomDemo {
19     public static void main(String[] args) {
20         // 创建对象
21         // Random r = new Random();
22         Random r = new Random(1111);// 给定种子,每次返回的随机数是一样的
23 
24         for (int x = 0; x < 10; x++) {
25             // int num = r.nextInt();
26             int num = r.nextInt(100) + 1;
27             System.out.println(num);
28         }
29     }
30 }

 程序演示效果,如下:

随机数范围是[1,100]([0,100)+1 ---> [1,100])

2. 利用Random实现获取任意范围的随机数案例(面试题)

代码如下:

package com.himi.random;

import java.util.Random;
import java.util.Scanner;

/*
 * 
 * 
 * 获取任意范围内的随机数
 * 构造方法:
 *        public Random():没有给种子,用的是默认种子,是当前时间的毫秒值
 *        public Random(long seed):给出指定的种子
 *        给定种子后,每次得到的随机数是相同的。
 *
 * 成员方法:
 *        public int nextInt():返回的是int范围内的随机数
 *        public int nextInt(int n):返回的是[0,n)范围的内随机数
 */
public class RandomDemo2 {
    public static void main(String[] args) {
       Scanner input = new Scanner(System.in);
       System.out.println("请输入开始数:");
       int start = input.nextInt();
       System.out.println("请输入结束数:");
       int end = input.nextInt();
       
       
       System.out.print("[");
       for(int i=0; i<20; i++) {
           if(i==19) {
               System.out.print(getRandom(start,end)+"]");
               break;
           }
           
           System.out.print(getRandom(start,end)+",");

       }
    }
    /**
     * 返回[start,end]区间中的随机整数
     * @param start
     * @param end
     * @return
     */

    private static int getRandom(int start, int end) {
        /**
         *[0,end-start+1)---->[start,end+1) == [start,end]
         */
        return new Random().nextInt(end-start+1)+start;
    }
}

程序运行结果如下:

原文地址:https://www.cnblogs.com/hebao0514/p/4837844.html