{
char[] charArray = {'a', 'b', 'a', 'c', 'a', 'd', 'e', 'b'};
int occurrences;
occurrences = countOccurrence(charArray, 'a', 0);
System.out.println("\"a\" occurred " + occurrences + " times.");
}
public static int countOccurrence(char[] array, char character, int index)
{
int counter = 0;
if (index > array.length-1)
{
//This probably seems a little awkward...But I have this here just so it stops
//recursion when it hits the end of the array.
}
else
{
if (array[index] == character)
{
counter++;
countOccurrence(array, character, index + 1);
}
else
{
countOccurrence(array, character, index + 1);
}
}
return counter;
}
嗨,由于某种原因,当我运行这个程序时,“a”出现的次数始终是 1...我尝试过以各种方式调整它,但我已经没有想法了。我在递归方面还是个新手。
最佳答案
您应该坚持使用简单的for
循环,而不是困惑的递归。
public static int countOccurrence(char[] array, char character)
{
int counter = 0;
for(int index = 0; index < array.length; ++index)
{
if (array[index] == character)
{
counter++;
}
}
return counter;
}
或者,如果您一心想使用递归:
当您的index
达到值array.length
时,只需终止递归即可。
也就是说,
public static int countOccurrence(char[] array, char character, int index)
{
int counter = 0;
if (index >= array.length)
return 0;
if (array[index] == character)
counter++;
counter += countOccurrence(array, character, index + 1);
return counter;
}
关于java - 我的递归方法无法正确返回 char 出现的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29045114/