我想写下代码以从预定义的字符串中生成5个字符的随机字符串。在Java中生成随机字符串,而不使用随机类或方法直接用于字符串
我的目标是创建一个长度为5的字符串数组,并将所有5个随机字符串存储在此数组中。
所以,到目前为止,我已经写了下面的代码:
public static String generateRandomString(int stringlength, String fullstring){
//Generating random number which will use to pick character from provider string at index[i]
int i =((int)(Math.random()*100));
//Created a character array to store the characters picked up from provided String
char [] randomString = new char[5];
//Checking the condition if generated random number is greater than or equals to string length to avoid OutOfBoundException
if (i>=stringlength){
generateRandomString(stringlength, fullstring);
}
//Else Fetching the character from provided string and storing it into Char[]
else
{
randomString [0] = (fullstring.charAt(i));
randomString [1] = (fullstring.charAt(i));
randomString [2] = (fullstring.charAt(i));
randomString [3] = (fullstring.charAt(i));
randomString [4] = (fullstring.charAt(i));
}
//Converting Char[] to String.
String returnString = new String(randomString);
//Returning String
return returnString;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//String Array to Store Random Strings
String [] array = new String[5];
//Provided String
String fullstring = "abcdefghijklmnopqrstuvwxyz";
int stringlength = fullstring.length();
//Loop to store random strings into all indexes of String[]
for(int j=0;j<5;j++){
array[j]=generateRandomString(stringlength, fullstring);
}
//Printing Final String[]
for(String var:array){
System.out.println(var);
}
}
但我现在面临两个问题:
- 我希望我的随机字符串不仅仅包含单个字符,我当前的代码对所有5个地方只挑选一个角色。因为它取一个值(i)。我想将(i)中的值更改为char []中每个存储了一个索引的字符后的任意随机值。
例如,
我正在“AAAAA”为一个随机字符串,但我想像“auzje”
- 当我打印最终的字符串[],有时我正在NULL字符串在我的输出。
例如, “”
“AAAAA”
“”
“GGGGG”
“IIIII”
什么我终于寻找的是:
“ ajsuh“
“ldugj”
“odueb”
“mcnde”
“yahnf”
请建议。
很多谢谢。
'randomString [0] =(fullstring.charAt(I)); randomString [1] =(fullstring.charAt(i)); randomString [2] =(fullstring.charAt(i)); randomString [3] =(fullstring.charAt(i)); randomString [4] =(fullstring.charAt(i));'是你的罪魁祸首。尝试调试为什么... – nullpointer