天天看点

生成任意随机数

1. 创建一个随机数对象的方法

/**
* Author:Liu Zhiyong
* Version:Version_1
* Date:2016年4月2日15:48:01
* Desc:产生随机数
     1.创建一个随机数对象
     2.调用随机数对象的nextInt方法
     3.导包
*/
import java.util.*;
class Demo8 
{
  public static void main(String[] args) 
  {
    //创建一个随机数对象
    Random random = new Random();
    //调用随机对象的nextInt方法,产生一个随机数
    int count = 15;
    while(count-- > 0){      
      int num = random.nextInt(11); //产生0~10(包括0和10)之间的随机数
      System.out.println("第"+(15-count)+"个随机数是_"+num);
    }
  }
}      

2.生成任意随机整数

package com.cn.test;
/**
* Author:Liu Zhiyong(QQ:1012421396)
* Version:Version_1
* Date:2017年2月27日10:07:29
* Desc:产生任意随机数
   通过Math.random()方法可以获取0到1之间的任意随机数,那如何获取任意给定的两个数之间的随机数呢?如获取2和9之间的随机数,5和10之间的随机数等。
   使用的方法有:Math.random()和Math.floor()
   
   Math对象常用的方法:
  ceil()    向上取整
  floor()   向下取整
  random()  返回 0 ~ 1 之间的随机数。(不包括边界值)
  round()   把数四舍五入为最接近的整数。
  ........
*/
public class RandomNumber {
  /**
   * @param args
   */
  public static void main(String[] args) {
    
    /**
     * 1. 产生0-1以内的double类型数字,不包括边界值。例如 0.00469724711275632,0.9761397031022399
     */
    for(int i=0; i<10; i++){
      double number = Math.random();
//      System.out.println(number);
    }
    
    /**
     * 2. 任意的int类型数字,包括边界值。例如2-9(2,3,4,……9)
     */
    int max = 9;
    int min = 2;
    for(int i=0; i<30; i++){
      int n1 = (int)(Math.random()*(max - min) + min);//生成2,3,4,……8数字
      n1 = (int)Math.floor(Math.random()*(max - min + 1) + min);//生成2,3,4,……9数字
//      System.out.println(n1);
    }    
  }
}