dan*_*309 8 java stack-overflow
所以程序必须计算字符串的字母。除了递归循环之外,我不允许使用循环。
该方法必须如下所示:
static int numberOf(String text, char characterToCount)
Run Code Online (Sandbox Code Playgroud)
输入:
abcbabcba(字符串)和 b(字符)
输出:
4
这就是我的代码到目前为止的样子(我得到 Stackoverflow ):
static int numberOf(String text, char characterToCount) {
int i = 0;
int erg = 0;
if (text.length() != 0) {
if (i != text.length()) {
if (text.charAt(i) == characterToCount) {
i++;
erg++;
numberOf(text, characterToCount);
} else {
i++;
numberOf(text, characterToCount);
}
} else {
return erg;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编辑
我只被允许使用String.charAt和String.length
问题是当你调用该方法时你没有减少文本,所以长度永远不会减少到 0。这是你应该做的。请注意,您不需要将索引传递给该方法。每次只将文本减少 1,然后检查第一个字符是否与目标字符相等。
public static void main(String[] args) {
System.out.println(numberOf("ksjssjkksjssss", 's'));
}
static int numberOf(String text, char characterToCount) {
if (text.isEmpty()) {
return 0;
}
if (text.charAt(0) == characterToCount) {
// call method and add 1 since you found a character
return numberOf(text.substring(1), characterToCount) + 1;
}
// just call the method.
return numberOf(text.substring(1), characterToCount);
}
Run Code Online (Sandbox Code Playgroud)
以上印
8
Run Code Online (Sandbox Code Playgroud)
好的,这是我修改后的版本,以满足您只使用String.length和 的要求String.charAt。char 实际上是 16 位,所以我使用高位字节来存储当前索引。我为每个递归调用增加该索引以保持搜索的当前位置。当我添加256到字符时,我实际上是在添加1到高位字节。
static int numberOf(String text, char ch) {
// stop when index exceeds text length
if (ch >> 8 >= text.length()) {
return 0;
}
if (text.charAt((ch >> 8)) == (ch & 0xff)) {
return numberOf(text, (char)(ch + 256)) + 1;
}
return numberOf(text, (char)(ch + 256));
}
Run Code Online (Sandbox Code Playgroud)
这不会像在某些宽度超过 8 位的字符集上写的那样工作。
所以我想我得到了我的解决方案。也许不是那么好,但它确实有效。感谢您的帮助 :)
public class CountLetters {
public static void main(String[] args) {
print("Bitte geben Sie den Text ein: ");
String text = readString();
text = toLowerCase(text, 0);
print("Bitte geben Sie ein Zeichen ein: ");
String zeich = readString();
zeich = toLowerCase(zeich, 0);
if (zeich.length() > 1) {
throw new PR1Exception("Bitte nur einen Buchstaben eingeben. ");
}
char zeichen = zeich.charAt(0);
if (zeichen > 0 && zeichen < 65 && zeichen > 90 && zeichen < 97 && zeichen > 123) {
throw new PR1Exception("Bitte nur Buchstaben eingeben.");
}
int anzahl = numberOf(text, zeichen);
println("-> " + anzahl);
}
static String toLowerCase(String text, int i) {
String lowerText = "";
if (i == text.length()) {
return lowerText;
} else if (text.charAt(i) < 'a') {
return lowerText += (char) (text.charAt(i) - 'A' + 'a') + toLowerCase(text, i + 1);
} else {
return lowerText += text.charAt(i) + toLowerCase(text, i + 1);
}
}
static int numberOf(String text, char characterToCount) {
return hilfe(text, characterToCount, 0, 0);
}
static int hilfe(String t, char ch, int i, int a) {
if (t.length() == a) {
return i;
} else if (t.charAt(a) == ch) {
return hilfe(t, ch, i + 1, a + 1);
} else {
return hilfe(t, ch, i, a + 1);
}
}
Run Code Online (Sandbox Code Playgroud)