Java为Character []添加随机字母

时间:2015-12-04 01:14:32

标签: java character

我有这个:

Character[] letters = new Character[30];

我想给它添加随机字母,这就是我正在做的事情:

Character[] letters = new Character[30];

Random r = new Random();

for (int i = 0; i < 30; i++){
char c = (char) (r.nextInt(26) + 'A');
System.out.printf("\nI: " + i + "C: "+c);

letters[i] = c; 
};

此外:

letters.add('A'); //doesn't work error: cannot find symbol add
letters[0] = 'A'; //this works

2 个答案:

答案 0 :(得分:1)

Java数组具有固定长度。要使用30个字符(基于for循环)填充数组,可以将Character[] letters = {};更改为

Character[] letters = new Character[30];

char[] letters = new char[30];

答案 1 :(得分:0)

一个班轮怎么样?

Character[] letters = Stream.generate(Random::new)
    .limit(30)
    .map(r -> new Character((char)(r.nextInt(26) + 'A')))
    .toArray(new Character[30]);