Java 產生隨機字串工具類。本站提醒廣大學習愛好者:此文章僅供參考,不一定能完全符合您的需求。以下是完整工具類正文
本文範例說明 Java 產生隨機數的方法。分享給大家供參考。具體實作方式如下:
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;
}
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);
System.out.println("重複率:" + rate);
}
}
主控台執行結果如下:
希望本文所述對大家的 Java 程式設計有所幫助。