2013-05-06 49 views
0
找到一個字符數組的大小

我剛開始的Java,我不明白爲什麼這樣的代碼:錯誤在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 

所有在第三行。爲什麼是這樣?有沒有另一種方法我應該找到一個字符數組的長度?

+0

'炭WORDS [] []'應'字符串中的單詞[]' – 2013-05-06 08:44:09

+1

在Java中,一個'炭[]'是不一樣的作爲'String'的東西。 – Jesper 2013-05-06 08:49:56

+0

與C風格字符串不同,字符序列不代表Java中的字符數組。另外,最後一行不是有效的Java。數組的長度必須在'char [] compHidden = new char [comp.length]'' – 2013-05-06 08:50:53

回答

0

的分配在這裏,像預期:

char compHidden[] = new char[comp.length]; 
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"}; 
+0

@SubhrajyotiMajumder'中用'new'指定,注意修正後的例子中數組被聲明爲String [] ' – 2013-05-06 08:48:46

+0

okeyz得到你的更新:) – 2013-05-06 08:49:27