如何实例化我的数组,使其中包含26个随机字符?
import java.util.Random;
public class Encryption {
Random r = new Random();
char[] real = {'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'};
char[] decrypted = //??????
for( i=0; i < decrypted.length; i++) {
}
答案 0 :(得分:2)
实例化大小为26的数组;
char[] array = new char[26];
添加随机字符(在小写字母范围内)
for(int i = 0; i < array.length; i++){
array[i] = (char)(r.nextInt(26) +97);
System.out.print(array[i]);
}
您可以通过删除随机部分并使用i
for(int i = 0; i < array.length; i++){
array[i] = (char)(i + 97);
System.out.print(array[i]);
}
答案 1 :(得分:0)
你应该查看这篇文章。它看起来像你正在寻找的答案。 How to generate a random alpha-numeric string?
答案 2 :(得分:0)
填写你的例子:
import java.util.Random;
public class Encryption {
Random r = new Random();
char[] real = {'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'};
char[] decrypted = new char[26];
public static void main(String[] args){
for( i=0; i < decrypted.length; i++) {
decrypted[i] = real[r.nextInt(26)];
}
}
}