我正在编写一个程序来计算字符串中字符出现的次数。这是我的方法:
public static int count (String line, char c)
{
int charOccurences = 0; //= 0;
for (int x = 0 ; x < line.length () ; x++)
{
if (line.charAt (x) == c)
{
charOccurences++;
line = line.substring (0, x) + line.substring (x + 1);
return count (line, c);
}
else
return charOccurences;
}
return charOccurences;
}
这段代码总是返回0,因为一旦该方法调用自身,它就会将charOccurences
重置为0。但我需要声明该变量才能使该方法正常工作。我无法想到任何解决办法。希望能得到任何帮助。