本文實例講述了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
|
package com.tool.code; import java.util.Random; public class RandomNum { private static char ch[] = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' , 'J' , 'K' , 'L' , 'M' , 'N' , 'O' , 'P' , 'Q' , 'R' , 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y' , 'Z' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' , '0' , '1' }; //最后又重復兩個0和1,因為需要湊足數組長度為64 private static Random random = new Random(); //生成指定長度的隨機字符串 public static String createRandomString( int length) { if (length > 0 ) { int index = 0 ; char [] temp = new char [length]; int num = random.nextInt(); for ( int i = 0 ; i < length % 5 ; i++) { temp[index++] = ch[num & 63 ]; //取后面六位,記得對應的二進制是以補碼形式存在的。 num >>= 6 ; //63的二進制為:111111 // 為什么要右移6位?因為數組里面一共有64個有效字符。 //為什么要除5取余?因為一個int型要用4個字節表示,也就是32位。 } for ( int i = 0 ; i < length / 5 ; i++) { num = random.nextInt(); for ( int j = 0 ; j < 5 ; j++) { temp[index++] = ch[num & 63 ]; num >>= 6 ; } } return new String(temp, 0 , length); } else if (length == 0 ) { return "" ; } else { throw new IllegalArgumentException(); } } //根據指定個數,測試隨機字符串函數的重復率 public static double rateOfRepeat( int number){ int repeat= 0 ; String[] str= new String[number]; for ( int i= 0 ;i<number;i++){ //生成指定個數的字符串 str[i]=RandomNum.createRandomString( 10 ); } for ( int i= 0 ;i<number;i++){ //查找是否有相同的字符串 for ( int j=i+ 1 ;j<number- 1 ;j++){ if (str[i].equals(str[j])) repeat++; } } return (( double )repeat)/number; } public static void main(String[] args) { System.out.println(RandomNum.createRandomString( 16 )+ "-" +RandomNum.createRandomString( 16 )); double rate=RandomNum.rateOfRepeat( 10000 ); //測試10000次的重復率 System.out.println( "重復率:" +rate); } } |
控制臺運行效果如下:
希望本文所述對大家的java程序設計有所幫助。