通过字符数组和循环字符循环
问题描述:
我试图优化我的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);
}
}
答
你的代码读取这样的: 对于每个角色在“检查” 如果字符在指数中的“检查”是在“元音”
索引字符这可能不是你要找的内容。你得到的例外是因为“元音”中只有5个字符,而“检查”中有很多(我不计数)
现在,我假设你想要做的是实际计数“检查”中每个元音的数量
在这种情况下,实际上应该使用嵌套for循环。
for (int i = 0; i < check.length(); i++) {
for (int v = 0; v < vowel.length; v++) {
if (check.charAt(i) == vowel[v]) {
counter[v]++;
break;
}
}
}
答
您必须具有两个环路 一为通过串字符每去和一个循环通过每个元音阵列会像这样
for (int i = 0; i < check.length(); i++)
for (int p = 0; p < vowel.length; p++)
if (check.charAt(i) == vowel[p])
counter[p]++;
享受。
+0
大声笑我知道对不起jst现在改变,难以在平板电脑 – 2014-10-11 11:15:30
答
for (int i = 0; i < check.length(); i++)
if (check.charAt(i) == vowel[i])
counter[i]++;
此回路从0
到check.length()
;但是你的数组vowel[]
有5个元素。所以它会产生数组超出界限的异常。
答
你可以使用正则表达式进行此操作:
Pattern vowels = Pattern.compile("(?i)[aeiou]");
String check = "Dit moet toch gewoon te doen zijn !!";
Matcher matcher = vowels.matcher(check);
while(matcher.find()) {
System.out.println("found vowel: " + matcher.group());
}
正则表达式的说明:
(?i)
使花纹不区分大小写,[aeiou]
字符相匹配。
答
还有一对聪明的正则表达式部门,所以你不必让您的字符串小写和失去的情况下元音:
if (check.matches("(?i)[^a-z][a-z].*"))
System.out.println("Vowels found: " + check.replaceAll("[^a-z]+", ""));
按照我的理解唯一的例外是在抛出:'如果(检查。 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