Random random = new Random()
Random random2 = new Random(long seed)
package dailytest;
import java.util.Random; import org.junit.Test; /** * Random類學習 * @author yrr * */ public class RandomTest { /** * 使用有參數構造生成Random對象 * 無論執行多少次,每次獲得的結果都相同 * -1157793070 * 1913984760 * 1107254586 */ @Test public void test01(){ Random random = new Random(10); for (int i = 0; i < 3; i++) { System.out.println(random.nextInt()); } } }
/**
* 測試Random類中的簡單方法
*/
@Test
public void test02() { Random random = new Random(); System.out.println("nextInt():" + random.nextInt()); //隨機生成一個整數,這個整數的範圍就是int類型的範圍-2^31~2^31-1 System.out.println("nextLong():" + random.nextLong()); //隨機生成long類型範圍的整數 System.out.println("nextFloat():" + random.nextFloat()); //隨機生成[0, 1.0)區間的小數 System.out.println("nextDouble():" + random.nextDouble()); //隨機生成[0, 1.0)區間的小數 byte[] byteArr = new byte[10]; random.nextBytes(byteArr); //隨機生成byte,並存放在定義的數組中,生成的個數等於定義的數組的個數 for (int i = 0; i < byteArr.length; i++) { System.out.println(byteArr[i]); } /** * random.nextInt(n) * 隨機生成一個正整數,整數範圍[0,n) * 若是想生成其餘範圍的數據,能夠在此基礎上進行加減 * * 例如: * 1. 想生成範圍在[0,n]的整數 * random.nextInt(n+1) * 2. 想生成範圍在[m,n]的整數, n > m * random.nextInt(n-m+1) + m * random.nextInt() % (n-m) + m * 3. 想生成範圍在(m,n)的整數 * random.nextInt(n-m+1) + m -1 * random.nextInt() % (n-m) + m - 1 * ...... 主要是依靠簡單的加減法 */ System.out.println("nextInt(10):" + random.nextInt(10)); //隨機生成一個整數,整數範圍[0,10) for (int i = 0; i < 20; i++) { //[3,15) //這裏有坑,須要注意,若是前面用了+號,應該要把計算結果總體用括號括起來,否則它會把+號解釋爲字符串拼接 System.out.println("我生成了一個[3,15)區間的數,它是:" + (random.nextInt(12) + 3)); } }
package dailytest;
import java.util.Random; import org.junit.Test; /** * Random類學習 * @author yrr * */ public class RandomTest { /** * 測試Random類中 JDK1.8提供的新方法 * JDK1.8新增了Stream的概念 * 在Random中,爲double, int, long類型分別增長了對應的生成隨機數的方法 * 鑑於每種數據類型方法原理是同樣的,因此,這裏以int類型舉例說明用法 */ @Test public void test03() { Random random = new Random(); random.ints(); //生成無限個int類型範圍內的數據,由於是無限個,這裏就不打印了,會卡死的...... random.ints(10, 100); //生成無限個[10,100)範圍內的數據 /** * 這裏的toArray 是Stream裏提供的方法 */ int[] arr = random.ints(10).toArray(); //生成10個int範圍類的個數。 System.out.println(arr.length); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } //生成5個在[10,100)範圍內的整數 random.ints(5, 10, 100).forEach(System.out :: println); //這句話和下面三句話功能相同 //forEach等價於: arr = random.ints(5, 10, 100).toArray(); for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } /** * 對於 * random.ints(); * random.ints(ori, des); * 兩個生成無限個隨機數的方法,咱們能夠利用Stream裏的terminal操做,來截斷無限這個操做 */ //limit表示限制只要10個,等價於random.ints(10) random.ints().limit(10).forEach(System.out :: println); //等價於random.ints(5, 10, 100) random.ints(10, 100).limit(5).forEach(System.out :: println); } }