java的运行时错误为ArrayIndexOutOfBoundsException:97
我有一个错误,有人能帮我吗。我试图打印字符串中出现频率最高的元音
void vowelCount() {
int countO = 0 ,countU = 0,countI = 0 ,countA = 0 ,countE = 0 ;
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
int[] count = new int[] {countA,countE,countI,countO ,countU};
int maxCount = 0;
char maximumChar = ' ';
for (int i = 0; i < TEXT.length(); i++) {
char ch = TEXT.charAt(i);
if (ch == vowels[0]) {
countA++;
}
if (ch == vowels[1]) {
countE++;
}
if (ch == vowels[2]) {
countI++;
}
if (ch == vowels[3]) {
countO++;
}
if (ch == vowels[4]) {
countU++;
}
}
for( int i = 0; i< vowels.length ; i++) {
if (count[vowels[i]] > maxCount) {
maxCount = count[vowels[i]];
maximumChar = vowels[i];
}
}
System.out.println();
System.out.println("The most used lowercase vowel is " + maximumChar + " for " + maxCount + " times.");
}
Arrayindexoutofbound异常结果,我不太确定哪里可以告诉我错误。尝试了这么长时间,错误仍然会重复
# 1 楼答案
您将得到一个
ArrayIndexOutOfBoundsException
,因为有以下几行:这里
vowels[i]
有字符,当您使用它作为count[vowels[i]]
时,您使用存储在vowels
数组中的字符的ascii值作为索引来访问count
数组中的值。 在例外情况下,打印97,因为它是字符“a”的ascii值您应该增加
count
数组数据,而不是变量countO, countU, etc..
变量。您还需要遍历count
数组,从中找到最大数,并将vowel
数组中的字符分配给maximumChar
变量# 2 楼答案
问题就在这里-
if (count[vowels[i]] > maxCount) {
vowels[i]
会给你一个元音,是char
。当用作从字符数组提取的索引时,字符将转换为其ASCII值,该值不在0到4的范围内我会说,你应该努力找出你的错误,而不是找到解决办法。下面的代码没有达到预期效果
当您使用
countX++
更新变量时,它不会修改存储在count[]
数组中的值,因为您已经使用0
初始化了它们,即countX
的初始值# 3 楼答案
我想说
count[vowels[i]]
是你的问题vowels[i]
将不在范围[0..4]
内,因此您超出了数组的边界。你想要的是count[i]
。您可以尝试下面的简化代码