Java中的随机数
? ? ? ? Java產生可以隨機數的有兩個類,一個是Random類,另一個是Math類中的random()方法。
一、Random類
? ? ? ? 在java.util包中有一個Random類,該對象的幾個方法可以生成不同數據類型的隨機數。如nextInt(),nextFloat(),nextLong(),nextBoolean()分別生成的是int整形,float浮點型,double浮點型,boolean布爾類型的隨機數,也必須要用制定的數據類型的變量接收。
? ? ? ? 例如:輸出五個隨機的布爾類型
import java.util.Random;public class Test01 {public static void main(String[] args) {Random rd = new Random();for(int i=0;i<5;i++) {boolean temp = rd.nextBoolean();System.out.println(temp);}} }????????
????????此外,可以生成int整形的nextInt()方法,有一個重載方法nextInt(int bound),多了一個傳入的bound整形,該方法可以使其生成[0,bound)區間的整形隨機數。bound不能<=0會報錯。
? ? ? ? 例如:隨機輸出5個0-99的隨機數。
import java.util.Random;public class Test01 {public static void main(String[] args) {Random rd = new Random();for(int i=0;i<5;i++) {int temp = rd.nextInt(100);System.out.println(temp);}} }? ? ? ? 輸出結果也是隨機的0-99:
? ? ? ? 我們發現,nextLong()同樣是生成整形的隨機數,但是沒有指定限制隨機區間的重載函數,那么就可以使用人為的方式來限制隨機區間。
? ? ? ? 1. nextLong()%n使其隨機數區間在(-n,n)
? ? ? ? 例如 : 輸出(-10,10)的5個隨機數。
import java.util.Random;public class Test01 {public static void main(String[] args) {Random rd = new Random();for(int i=0;i<5;i++) {Long temp = rd.nextLong()%10;System.out.println(temp);}} }????????
? ? ? ? 2.使用 Math.abs()? 限制隨機數為非負數。
? ? ? ? 例如:輸出5個 0-9的隨機數
public class Test01 {public static void main(String[] args) {Random rd = new Random();for(int i=0;i<5;i++) {Long temp = Math.abs( rd.nextLong())%10;System.out.println(temp);}} }?????????其中的nextFloat(),nextDouble()方法分別生成0-1的8位有限小數,16位有限小數的隨機數。
? ? ? ? 例如:輸出5個16位有限小數的隨機數。
public class Test01 {public static void main(String[] args) {Random rd = new Random();for(int i=0;i<5;i++) {double temp = Math.abs( rd.nextDouble())%10;System.out.println(temp);}} }????????
二、Math.random()方法
? ? ? ? 生成的隨機數和Random類的nextDouble()類似,也是16位有限小數。
? ? ? ? 例如:輸出5個0-1區間的16位有限小數的隨機數。
import java.util.Random;public class Test01 {public static void main(String[] args) {Random rd = new Random();for(int i=0;i<5;i++) {double temp = Math.random();System.out.println(temp);}} }總結
- 上一篇: Bean复制的几种框架性能比较(Apac
- 下一篇: java美元兑换,(Java实现) 美元