3 回答
TA贡献1821条经验 获得超6个赞
您可以使用 Apache Commons Lang 生成字母字符串
String generatedString = RandomStringUtils.randomAlphanumeric(10);
尝试这样的事情
Hashtable<Integer, String> Deck = new Hashtable();
for (int i = 0; i < 10; i++) {
String generatedString = RandomStringUtils.randomAlphanumeric(10);
int key = (int) (Math.random() *52) ;
Deck.put(key, generatedString);
}
System.out.println(Deck);
输出
{9=Ut7N87oMNp, 8=7kbARh5WIy, 7=pbU2ZCOGK1, 6=vAGAIw41Us, 5=VLnpY1FAuN, 4=UEIJNIvZlt, 3=z6Y3zXcDY1, 2=PxaMqXl8XW, 1=l72bkPdY6T, 0=FFdOsKpQgd}
如果你只想要 Alphabets 然后使用RandomStringUtils.randomAlphabetic(10);instaed of RandomStringUtils.randomAlphanumeric(10)。
如果您不想要第三方 api,那么您的代码片段会进行一些更改
while (k < 4) {
for (int j = 1; j <= 13; j++) {
Hashtable<Integer, String> Deck = new Hashtable();
StringBuilder sb = new StringBuilder();
int cnt = 0;
while (cnt++ != 10) {
int myChar = (int) (Math.random() * str.length());
sb.append(str.charAt(myChar));
}
int i = (int) (Math.random() * 52);
Deck.put(i, sb.toString());
System.out.print(Deck);
}
System.out.println();
k++;
}
仅添加了while循环...
TA贡献1811条经验 获得超5个赞
您可以使用以下代码生成随机字符串。
private static final String ALPHA_STRING = "abcdefghijklmnopqrstuvwxyz";
public static String randomString(int count) {
StringBuilder builder = new StringBuilder();
while (count-- != 0) {
int character = (int) (Math.random() * ALPHA_STRING.length());
builder.append(ALPHA_STRING.charAt(character));
}
return builder.toString();
}
public static void main(String[] arg) {
Hashtable<Integer, String> Deck = new Hashtable();
for (int j = 1; j <= 10; j++) {
Deck.put(j, randomString(12));
}
System.out.println(Deck);
}
输出
{10=upjolkfihcyh, 9=irpbrcoclcmx, 8=ppugclscjlja, 7=wtnvkpmocuwd, 6=gpyzppvywazp, 5=vosixtjvcqlg, 4=plwtzzjpzeoq, 3=wsdyyppphhng, 2=knqdzfctfnez, 1=jzakqfiksrho}
TA贡献1848条经验 获得超2个赞
尝试使用以下代码使用随机方法生成唯一密钥。
private char[] uniqueKeyGenerator(int len) {
String Capital_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String Small_chars = "abcdefghijklmnopqrstuvwxyz";
String numbers = "0123456789";
String values = Capital_chars + Small_chars + numbers;
// Using random method
Random rndm_method = new Random();
char[] password = new char[len];
for (int i = 0; i < len; i++) {
password[i] = values.charAt(rndm_method.nextInt(values.length()));
}
return password;
}
添加回答
举报