java Random.nextInt()方法
用法:
java Random.nextInt()方法
会随机生成一个整数,这个整数的范围就是int类型的范围-2^31 ~ 2^31-1,但是如果在nextInt()括号中加入一个整数a那么,这个随机生成的随机数范围就变成[0,a)。
用例
1 package org.xiaowu.random.demo; 2 3 import java.util.Random; 4 5 import org.junit.Test; 6 7 public class RandomDemo { 8 9 @Test 10 public void Demo(){ 11 Random rnd = new Random(); 12 int code = rnd.nextInt(8999) + 1000; 13 System.out.println("code:"+code); 14 } 15 16 17 @Test 18 public void Demo1(){ 19 Random r = new Random(); 20 int nextInt = r.nextInt(); 21 Random r1 = new Random(10); 22 int nextInt2 = r1.nextInt(); 23 System.out.println("nextInt:"+nextInt); 24 System.out.println("nextInt2:"+nextInt2); 25 } 26 27 28 /** 29 * 生成[0,1.0)区间的小数 30 * 31 */ 32 @Test 33 public void Demo2(){ 34 Random r = new Random(); 35 double d1 = r.nextDouble(); 36 System.out.println("d1:"+d1); 37 } 38 39 40 /** 41 * 生成[0,5.0)区间的小数 42 * 43 */ 44 @Test 45 public void Demo3(){ 46 Random r = new Random(); 47 double d2 = r.nextDouble()* 5; 48 System.out.println("d1:"+d2); 49 } 50 51 52 /** 53 * 生成[1,2.5)区间的小数 54 * 55 */ 56 @Test 57 public void Demo4(){ 58 Random r = new Random(); 59 double d3 = r.nextDouble() * 1.5 + 1; 60 System.out.println("d1:"+d3); 61 } 62 63 64 /** 65 * 生成任意整数 66 * 67 */ 68 @Test 69 public void Demo5(){ 70 Random r = new Random(); 71 int n1 = r.nextInt(); 72 System.out.println("d1:"+n1); 73 } 74 75 76 77 /** 78 * 生成[0,10)区间的整数 79 * 80 */ 81 @Test 82 public void Demo6(){ 83 Random r = new Random(); 84 int n2 = r.nextInt(10); 85 int n3 = Math.abs(r.nextInt() % 10); 86 System.out.println("n2:"+n2); 87 System.out.println("n3:"+n3); 88 } 89 90 91 92 /** 93 * 生成[0,10]区间的整数 94 * 95 */ 96 @Test 97 public void Demo7(){ 98 Random r = new Random(); 99 int n3 = r.nextInt(11); 100 int n4 = Math.abs(r.nextInt() % 11); 101 System.out.println("n3:"+n3); 102 System.out.println("n4:"+n4); 103 } 104 105 106 /** 107 * 生成[-3,15)区间的整数 108 * 109 */ 110 @Test 111 public void Demo8(){ 112 Random r = new Random(); 113 int n4 = r.nextInt(18) - 3; 114 int n5 = Math.abs(r.nextInt() % 18) - 3; 115 System.out.println("n4:"+n4); 116 System.out.println("n5:"+n5); 117 } 118 119 }