首页 > 代码库 > java之Random类
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类