我需要帮助创建一个包含2个参数的随机字符串数组:
我是否需要嵌套for循环?
一切都会有所帮助,谢谢!
答案 0 :(得分:0)
你可以使用嵌套循环来实现,正如你在问题中所说:
public String[] randomArrayString(int length, int numberOfChar) {
Random random = new Random();
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
String[] array = new String[length];
String str;
for (int i = 0; i < length; i++) {
str = "";
for (int j = 0; j < numberOfChar; j++) {
str+= chars[random.nextInt(chars.length - 1)];
}
array[i] = str;
}
return array;
}
您也可以使用Java 8 Streams制作解决方案,如下所示:
public Object[] randomArrayString(int length, int numberOfChar){
Random random = new Random();
char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
return Stream.generate(() -> {
String str="";
for (int i = 0; i < numberOfChar; i++) {
str+= chars[random.nextInt(chars.length - 1)];
}
return str;
}).limit(length).toArray();
}