复制代码

为懒人提供无限可能,生命不息,code不止

人类感性的情绪,让我们知难行难
我思故我在
日拱一卒,功不唐捐
  • 首页
  • 前端
  • 后台
  • 数据库
  • 运维
  • 资源下载
  • 实用工具
  • 接口文档工具
  • 登录
  • 注册

jdk

【原创】java随机数生成,random()生成随机数,nextInt(int n)生成随机数,nextInt()生成随机数

作者: whooyun发表于: 2017-03-20 00:39

先对java中随机数操作做一个简单的介绍:
调用java里Math类的random()方法返回0.0到1.0之间的double随机数
调用Random类的nextInt(int n)方法返回0(包括0)到n范围内的int随机数
调用Random类的nextInt()方法返回无限制的int随机数。

在日常开发中我们通常会遇到以下问题:
1、如何生成一个java随机数
2、如何生成一个在指定范围内的java随机数
3、有没有地方能找到一个生成随机数的例子
4、Java.lang.Math.random() 实例就可以生成随机数
(以上都是国外网站翻译过来,翻译有点别扭,请见谅)

以下为 Random() 函数使用的具体实例:
先建一个RandomTest1()方法,用来打印最小到最大的随机数
再建一个RandomTest2()方法,用来打印list中的随机数

最后在main方法中建俩个线程,并运行

package com.crunchify.tutorials;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
/**
 * @author Crunchify.com
 * 
 */
 
public class CrunchifyRandomNumber {
 
	// Simple test which prints random number between min and max number (Number
	// Range Example)
	public void RandomTest1() throws InterruptedException {
		while (true) {
			int min = 5;
			int max = 15;
 
			float randomNumber = (min + (float) (Math.random() * ((max - min))));
			System.out.println("Test1: " + randomNumber);
			Thread.sleep(500);
		}
	}
 
	// Simple test which prints random entry from list below
	public void RandomTest2() throws InterruptedException {
		List<String> list = new ArrayList<String>();
		list.add("eBay");
		list.add("Paypal");
		list.add("Google");
 
		Random randomNumber = new Random();
		String randomEle;
		int listSize = list.size();
 
		while (true) {
			randomEle = list.get(randomNumber.nextInt(listSize));
			System.out.println("Test2: " + randomEle);
			Thread.sleep(800);
		}
	}
 
	static public void main(String[] args) {
 
		// Let's run both Test1 and Test2 methods in parallel..
		Thread thread1 = new Thread() {
			public void run() {
				CrunchifyRandomNumber cr = new CrunchifyRandomNumber();
				try {
					cr.RandomTest1();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		Thread thread2 = new Thread() {
			public void run() {
				CrunchifyRandomNumber cr = new CrunchifyRandomNumber();
				try {
					cr.RandomTest2();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		thread1.start();
		thread2.start();
	}
}
以下为代码输出结果

random()生成随机数,nextInt(int n)生成随机数,nextInt()生成随机数,这三者都是有区别的,希望大家注意。