我试图优化我的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