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);
}
}
}