随机字符生成器存储在数组中

时间:2014-01-30 21:47:41

标签: java arrays loops encryption

如何实例化我的数组,使其中包含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++) {

}

3 个答案:

答案 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)];
    }
  }
}