• java中产生随机数的几种方法


    方法一:

    public class RandomTest
    {
        public static void main(String[] args)
        {
            int i = (int) (Math.random()*100);
            System.out.println(i);
        }
            
    }

    这里的100代表的就是你需要产生数据的范围是多少;利用了Math类的random方法;

    而random方法产生的数据为double类型的,范围为:0.0--1.0,所以需要强制类型转换为int类型的;


    方法二:

    public class RandomTest
    {
        public static void main(String[] args)
        {
            Random random = new Random();
            
            int i = random.nextInt(2);
            
            System.out.println(i);
        }
            
    }

    此方法利用了random中的nextInt(int)(即带种子)方法;nextInt方法接收一个整数使得随机产生的数的范围为0--n-1;

    上述两种方法比较简单,下面有一个比较复杂的方法

    出处为:http://www.51testing.com/?117708/action_viewspace_itemid_11637.html

         不带种子的方法产生的是随机的毫秒数;

    Random random = new Random();
            
            for(int i=0;i<1;i++)
            {
                
                System.out.println(random.nextInt());
            }

    i控制的是数据的个数;










  • 相关阅读:
    十一作业
    11.20
    11.13 第十二次、
    11.13 第十一次、
    11.06第十次、
    11.06第九次、
    10.30
    10.23
    10.16
    10.9
  • 原文地址:https://www.cnblogs.com/penggy/p/7475869.html
Copyright © 2020-2023  润新知