java隨機數的產生比較簡單,可以通過
1
2
|
Random rand = new Random( 47 ); System.out.println(rand.nextInt()); |
產生,也可以通過以下產生:
1
|
double d = Math.random(); |
當然代碼中前者由于使用了固定的種子47,所以每次的值都是一樣的,也可以使用
1
2
|
Random rand = new Random(); System.out.println(rand.nextInt()); |
而對于代碼2則產生的是double的隨機數。
下面說下關于3的方式,目前有個需求就是需要產生4為隨機數,用于短信注冊碼的生成,那么就需要使用到隨機數,于是使用代碼3來實現。若之間使用該代碼那么結果并不能滿足條件,那么通過以下方式來實現:
1
2
3
4
5
6
7
8
9
10
11
12
|
//方式一 Random rand = new Random(); for ( int i = 0 ; i < 4 ; i++){ System.out.print(Math.abs(rand.nextint() % 10 )); } //以上通過rand.next產生隨機數,因可能存在負數,用Math.abs取絕對值,然后取模10,產生的結果在10以內 //方式二 Random rand = new Random(); for ( int i = 0 ; i < 4 ; i++){ System.out.print(rand2.nextint( 10 )); } //以上使用api直接產生10以內的隨機數 |
自己最近寫的一個JAVA隨機數模塊,封裝了各種與隨機相關的實用方法,特拿來分享。
這里面沒什么高科技的東西,函數命名也能看出來用途,所以就簡單的注釋一下好了,有什么問題可以留言。
源代碼(RandomSet.java):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
import java.awt.Color; import java.util.Collection; import java.util.Iterator; import java.util.Random; public class RandomSet { static Random random = new Random(); //獲得一個給定范圍的隨機整數 public static int getRandomNum( int smallistNum, int BiggestNum) { return (Math.abs(random.nextint())%(BiggestNum-smallistNum+ 1 ))+smallistNum; } //獲得一個隨機的布爾值 public static Boolean getRandomBoolean() { return (getRandomNum( 0 , 1 ) == 1 ); } //獲得一個隨機在0~1的浮點數 public static float getRandomFloatIn_1() { return ( float )getRandomNum( 0 , 1000 )/ 1000 ; } //獲得一個隨機的顏色 public static Color getRandomColor() { float R = ( float )getRandomNum( 0 , 255 )/ 255 ; float G = ( float )getRandomNum( 0 , 255 )/ 255 ; float B = ( float )getRandomNum( 0 , 255 )/ 255 ; return new Color(R,G,B); } //以一定概率返回一個布爾值 public static Boolean getRate( int rate) { if (rate< 0 || rate > 100 ) { return false ; } else { if (getRandomNum( 0 , 100 )<rate) { return true ; } else { return false ; } } } //返回給定數組中的一個隨機元素 public static <T> T getElement(T[] t) { int index = getRandomNum( 0 ,t.length - 1 ); return t[index]; } //返回給定Collection中的一個隨機元素 public static <T> T getElement(Collection<? extends T> c) { int atmp = getRandomNum( 0 ,c.size() - 1 ); Iterator<? extends T> iter = c.iterator(); while (atmp > 0 ) { atmp--; iter.next(); } return iter.next(); } } |
總結
以上就是本文關于Java編程一個隨機數產生模塊代碼分享的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/shuzhe66/article/details/26989481