我試圖優化我的Java代碼,所以我嘗試了一些東西。在我的簡短搜索中,我在下面編寫了代碼。這會拋出一個Exception
。你能告訴我爲什麼嗎?我不能通過char數組來循環一個字符串嗎?通過字符數組和循環字符循環
public class Input {
public static void main(String[] args) {
String check = "Dit moet toch gewoon te doen zijn !!";
check = check.toLowerCase();
int[] counter = {0, 0, 0, 0, 0};
char[] vowel = {'a', 'e', 'i', 'o', 'u'};
int total = 0;
for (int i = 0; i < check.length(); i++)
if (check.charAt(i) == vowel[i])
counter[i]++;
for (int t : counter)
total += t;
System.out.println("Aantal klinkers: \t" + total);
}
}
按照我的理解唯一的例外是在拋出:'如果(檢查。 charAt(i)==元音[i])' – 2014-10-11 11:03:52
您已將字符串與元音數組的長度混合在一起。 – blackSmith 2014-10-11 11:04:14
「counter」和「vowel」有5個元素,「check」有30個元素。換句話說,你的循環沒有被正確構建。 – Keppil 2014-10-11 11:04:16