在Java中查找char数组的大小时出错

时间:2013-05-06 08:41:39

标签: java arrays

我刚刚开始使用Java,我不明白为什么会这样的代码:

char WORDS[][] = {"jazz", "buzz", "hajj", "fuzz", "jinx", "jazzy", "fuzzy", "faffs", "fizzy", "jiffs", "jazzed", "buzzed", "jazzes", "faffed", "fizzed", "jazzing", "buzzing", "jazzier", "faffing", "fuzzing"};
char comp[] = WORDS[rand.nextInt(WORDS.length)];
char compHidden[comp.length];

产生此错误:

- Syntax error on token "[", = expected
- Type mismatch: cannot convert from int 
 to char
- Syntax error on token "]", delete this 
 token

全部在第三行。为什么是这样?我还有另一种方法可以找到char数组的长度吗?

2 个答案:

答案 0 :(得分:0)

此处需要进行分配,例如:

char compHidden[] = new char[comp.length];

答案 1 :(得分:0)

WORDS数组未实例化为多维数组,而是实例化为常规char[],并且应该声明为此类数组。同样,数组的类型不应该是char[],而应该是String[]给定分配的数组类型。

变化:

char WORDS[][] = {"jazz", "buzz", "hajj", "fuzz", "jinx", "jazzy", "fuzzy", "faffs", "fizzy", "jiffs", "jazzed", "buzzed", "jazzes", "faffed", "fizzed", "jazzing", "buzzing", "jazzier", "faffing", "fuzzing"};

String WORDS[] = {"jazz", "buzz", "hajj", "fuzz", "jinx", "jazzy", "fuzzy", "faffs", "fizzy", "jiffs", "jazzed", "buzzed", "jazzes", "faffed", "fizzed", "jazzing", "buzzing", "jazzier", "faffing", "fuzzing"};