我试图使用char数组计算字符串中元音的数量,但每当我比较两者时,我都会收到一条消息。在我的for循环中,我要么让它计数一个像"hello"这样的小字符串,这是一个根本不计数的错误,要么它达到了一个越界异常。不确定我做错了什么。
public class App
{
public static int vowelCounter(String myString)
{
if(myString.length() > 0)
{
char vowelArray[] = {'A','E','I', 'O', 'U', 'a', 'e', 'i', 'o', 'u'};
int countedVowels = 0;
for(int i = 0; myString.length() > 0; i++)
{
//The if statement below seems to work until the string gets too big. You then get an Out of Bounds exception error.
//eIf i don't put the 'i' in the index for vowelArray, the count will not increase.
if(myString.contains(myString.valueOf(vowelArray[i])))
{
countedVowels++;
}
else
{
return 0;
}
}
return countedVowels;
}
else
{
return 0;
}
}
}
不要使用i
作为变量名,而是使用更有意义的名称。然后你的虫子就会跳出来攻击你。
for( int indexIntoMyString = 0; myString.length() > 0; indexIntoMyString ++ )
…
if( myString.contains( myString.valueOf( vowelArray[ indexIntoMyString ] ) ) )
提示:
- 你没有循环你的元音数组
- 了解嵌套循环
顺便说一句,char
类型是遗留的,从Java 2开始就基本上被破坏了。作为一个16位的值,char
在物理上不能表示大多数字符。
要使用单个字符,请学习使用代码点整数。
for循环的条件'myString.length((>"0"总是"true",因为你既没有最小化myString,也没有最小化它的长度。这就是为什么你的i会无限增加,你的索引i会超出vowelArray的范围。
您应该使用两个循环,一个用于遍历字符串,另一个用于vowelArray。类似这样的东西:
public class App {
public static final char[] VOWELS = {'a', 'e', 'i', 'o', 'u'};
public static int vowelCounter(String myString) {
if (!myString.isEmpty()) {
int countedVowels = 0;
myString = myString.toLowerCase();
char[] word = myString.toCharArray();
for (int i = 0; i < word.length; i++) {
char currentChar = word[i];
for (char c : VOWELS) {
if (currentChar == c){
countedVowels++;
}
}
}
return countedVowels;
} else {
return 0;
}
}
}
或者使用像这个一样的集合
public class App {
public static final Set<Character> VOWELS = Set.of('a', 'e', 'i', 'o', 'u');
public static int vowelCounter(String myString) {
if (!myString.isEmpty()) {
int countedVowels = 0;
myString = myString.toLowerCase();
char[] word = myString.toCharArray();
for (char c : word) {
if (VOWELS.contains(c)) {
countedVowels++;
}
}
return countedVowels;
} else {
return 0;
}
}
}