zoukankan      html  css  js  c++  java
  • 《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);
    		}

  • 相关阅读:
    二分查找binarySearch
    快速排序quicksort实现方法
    读书清单
    windows 下遍历文件夹
    如何输出 android.mk 及 Application.mk 中个变量的值
    【转】 armeabi与armeabi-v7a
    Application.mk
    【转】TypeError: 'module' object is not callable 原因分析
    User breakpoint called from code at XXX的解决方式记录
    关于溢出的一些体会
  • 原文地址:https://www.cnblogs.com/wanghang/p/6299812.html
Copyright © 2011-2022 走看看