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

java之Random类

时间:2016-10-11 22:15:37      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:java之random类

1.Random类概述及其构造方法

  此类用于产生随机数。

  如果用相同的 种子创建两个Random实例,则对每个实例进行相同的方法调用序列,他们将生成并返回相同的数字序列。


2.构造方法

  public Random()

  public Random(omt seed) //seed种子数

package cn;

import java.util.Random;

/**
 * Random类 
 *	构造方法
 *	public Random()
 *	public Random(int seed)
 */
public class RandomDemo {
	public static void main(String[] args) {
		Random r1 = new Random();
		Random r2 = new Random();
		for (int i = 0; i < 10; i++) {
			int num1 = r1.nextInt();
			System.out.println(num1+" ");
		}
		System.out.println("********************");
		for (int i = 0; i < 10; i++) {
			int num2 = r2.nextInt();
			System.out.println(num2+" ");
		}
	}

}

结果显示:

51213552 

1362284309 

-527965968 

854768376 

-1846321813 

2113648182 

-153433014 

220802460 

165595671 

115275732 

********************

-1948449190 

701552025 

1803374548 

1035375708 

-1766843659 

-385282587 

1371526123 

1575737858 

2099677771 

2125562112 

package cn;

import java.util.Random;

/**
 * Random类 
 *	构造方法
 *	public Random()
 *	public Random(int seed)
 */
public class RandomDemo {
	public static void main(String[] args) {
		Random r1 = new Random(10);
		Random r2 = new Random(10);
		for (int i = 0; i < 10; i++) {
			int num1 = r1.nextInt();
			System.out.println(num1+" ");
		}
		System.out.println("********************");
		for (int i = 0; i < 10; i++) {
			int num2 = r2.nextInt();
			System.out.println(num2+" ");
		}
	}

}

结果显示:

-1157793070 

1913984760 

1107254586 

1773446580 

254270492 

-1408064384 

1048475594 

1581279777 

-778209333 

1532292428 

********************

-1157793070 

1913984760 

1107254586 

1773446580 

254270492 

-1408064384 

1048475594 

1581279777 

-778209333 

1532292428 


3.类成员方法

  public int nextInt()

  public int nextInt(int n)

package cn;

import java.util.Random;

/**
 * Random类 
 *	构造方法
 *		public Random()
 *		public Random(int seed)
 *  类成员方法
 *  	public int nextInt() //调用此方法,将会在int数据类型范围内产生随机数
 *  	public int nextInt(int n)//调用次方法,将会在[0,n)之间的范围内产生随机数
 */
public class RandomDemo {
	public static void main(String[] args) {
		Random r1 = new Random();
		for (int i = 0; i < 10; i++) {
			int num1 = r1.nextInt();
			System.out.println(num1+" ");
		}
		
		System.out.println("*******************");
		
		Random r2 = new Random();
		for (int i = 0; i < 10; i++) {
			int num2 = r2.nextInt(10);
			System.out.println(num2+" ");
		}
		
		
	}

}



本文出自 “11831428” 博客,请务必保留此出处http://11841428.blog.51cto.com/11831428/1860745

java之Random类

标签:java之random类

原文地址:http://11841428.blog.51cto.com/11831428/1860745

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