码迷,mamicode.com
首页 > 编程语言 > 详细

Java产生随机数

时间:2017-10-17 20:32:22      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:blog   随机   ide   opened   sed   double   math   pre   math类   

  对于这个问题,我只放上代码就可以了,代码中有注释,相信聪明的你看得懂的!

  

技术分享
import java.util.Random; //需要用到这个类包
/*
 * Java产生随机数
 * Time:2017/10/16
 *
 * 方法一:Math类中的random方法可以实现随机数的生成
 * Math.random()方法返回的是带正号的double值,该值大于0小于1。
 * 当然,我们也可以做修改:
 *                         (int)(Math.random()*10)   返回0-9之间的随机数
 *                         (int)(Math.random()*n)       返回0-n之间的随机数
 *                         (int)(Math.random()*100)+1        返回0-100之间的随机数,前面返回0-99,加1就是0-100了
 *
 * 方法二:Random类
 * 在生成随机数之前,必须先写:Random random=new Random();
 * random.nextInt();    返回的是int类型范围内的随机数
 * random.nextInt(10);    返回的是0-9之间的随机数
 * random.nextInt(100)+1;    返回的是1-100之间的随机数
 * random.nextInt(n)+m;        返回的就是m到m+n-1之间的随机数
 */
public class RandomNum {
    public static void main(String[] args) {
        //方法一
        double num=Math.random();//返回double类型的数字
        System.out.println(num);
        //以下生成int类型的如果不把方法括起来,返回的只能是0
        int num1=(int)(Math.random()*10);//返回0-9之间的随机数
        System.out.println(num1);
        int num2=(int)(Math.random()*100);//返回0-99之间的额数
        System.out.println(num2);

        //方法二
        Random random=new Random();//方法二就必须写这句,random只是个名字,自己取
        int s=random.nextInt();//生成一个int类型的随机数
        System.out.println("生成的随机数为:"+s);
        int s2=random.nextInt(10);//生成0-9之间的随机数
        System.out.println(s2);
    }
}
View Code

  运行结果为:

  

0.3248983535648986
6
91
生成的随机数为:-1909871388
6

 

Java产生随机数

标签:blog   随机   ide   opened   sed   double   math   pre   math类   

原文地址:http://www.cnblogs.com/dream-saddle/p/7683675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!