• 《java入门第一季》之Random类和获取随机数案例


    /*
     * Random:产生随机数的类
     * 
     * 构造方法:
     * public Random():没有给种子,用的是默认种子,是当前时间的毫秒值下的随机数,所以会一直变化
     * public Random(long seed):给出指定的种子    long  seed就是一个long类型的数据而已

     * 给定种子后,每次得到的随机数是(相同的)。再次编译执行后的数据不变了。

    *              种子是什么,又怎么变与不变?根据例子说明。

    */

    public class RandomDemo {
    	public static void main(String[] args) {
    		// 创建对象
    		Random r1 = new Random();//没给种子
    		Random r = new Random(111);//long 给的种子不同
    
    		//随机获取10个1-100的随机数
    		for (int x = 0; x < 10; x++) {
    			// int num = r.nextInt();
    			int num = r.nextInt(100) + 1;
    			System.out.println(num);
    		}
    		System.out.println("--------------------------");
    		for(int x = 0; x < 10; x++){
    			int num = r1.nextInt(100) + 1;
    			System.out.println(num);
    		}
    	}
    }

    输出结果:

    294
    971
    958
    698
    410
    921
    285
    613
    598
    966
    --------------------------
    857
    683
    744
    768
    282
    613
    23
    743
    763
    414


    再一次编译输出结果:

    294
    971
    958
    698
    410
    921
    285
    613
    598
    966
    --------------------------
    751
    924
    654
    376
    20
    95
    563
    576
    43
    108

    这个时候什么是种子,什么是不变与变化的区别一目了然了吧。


    同时,利用Random获取1-100的另一种方式也已经完成了。即上面的几行代码:

    for (int x = 0; x < 10; x++) {
    			// int num = r.nextInt();
    			int num = r.nextInt(100) + 1;
    			System.out.println(num);
    		}

  • 相关阅读:
    CSS使用规则总结
    python虚拟机内存泄露?
    对象内存池
    由引擎接口自顶向下的设计引擎结构
    【译】Lesson 0: 开始学习WebGL
    【译】Lesson 1: 一个三角形和一个方块
    网盘中搭建git服务
    行为树(Behavior Tree)
    显卡参数大全
    VTune 备忘
  • 原文地址:https://www.cnblogs.com/wanghang/p/6299812.html
Copyright © 2020-2023  润新知