我正在我的compsci类中创建一个需要完成此任务的方法:
“写一个称为String的递归方法buildWeirdString(String s)在构建原始字符串的“正向”部分时,它不应保留原始字符串的任何数字-在构建原始字符串的“向后”部分时,它不应保留初始输入中包含的任何字母(您应该发现我们在课堂上做过的reverseLine()方法很有用)忽略大小写的微小提示– Character类中有一个有用的方法告诉您字符是否为字母,例如
用户输入:abCD123e!$ f%
会产生输出:abCDe!$ f%$!321
我不完全知道如何使用Stringbuilder类,因为我们还没有在课堂上讲过它,但是看来它对这个应用程序很有用,所以很可能我的错误是它的用法但很可能在其他任何地方。
此任务从“静态字符串” buildWeirdString开始,其余是其他已完成的任务。
package recursionPrograms;
import java.util.*;
public class recursion {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
Scanner st = new Scanner(System.in);
int b = 0;
int e = 0;
String str;
String string;
// exp
System.out.println("Base: ");
b = s.nextInt();
System.out.println("Exponent: ");
e = s.nextInt();
System.out.println(recPow(b, e));
// palidrome
System.out.println("String: ");
str = st.nextLine();
System.out.println(isPalindrome(str));
//string
System.out.println("String: ");
string = st.nextLine();
System.out.println(buildWeirdString(string));
}
public static double recPow(int base, int exp) {
if (exp == 0)
return 1;
else if (exp < 0)
return 1 / (base * recPow(base, Math.abs(exp) - 1));
else
return base * recPow(base, exp - 1);
}
static boolean isPalindrome(String str) {
if (str.length() < 2) {
return true;
}
if (str.charAt(0) == str.charAt(str.length() - 1)) {
return isPalindrome(str.substring(1, (str.length() - 1)));
}
return false;
}
static String buildWeirdString(String string) {
StringBuilder stb = new StringBuilder();
StringBuilder stb2 = new StringBuilder();
if (string.length() == 0) {
String rtrn = stb.toString() + stb2.reverse().toString();
return rtrn;
}
if (Character.isLetter(string.charAt(0))) {
buildWeirdString(string.substring(1));
stb.insert(string.length() - 1,
Character.toString(string.charAt(0)));
}
if (!Character.isLetter(string.charAt(0))) {
buildWeirdString(string.substring(1));
stb2.insert(string.length() - 1,
Character.toString(string.charAt(0)));
}
return null;
}
}
所需结果: 在:abc1d234 出:abcd4321
会发生什么:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.AbstractStringBuilder.insert(Unknown Source)
at java.lang.StringBuilder.insert(Unknown Source)
at recursionPrograms.recursion.buildWeirdString(recursion.java:62)
at recursionPrograms.recursion.buildWeirdString(recursion.java:61)
at recursionPrograms.recursion.buildWeirdString(recursion.java:61)
at recursionPrograms.recursion.buildWeirdString(recursion.java:57)
at recursionPrograms.recursion.buildWeirdString(recursion.java:57)
at recursionPrograms.recursion.buildWeirdString(recursion.java:57)
at recursionPrograms.recursion.buildWeirdString(recursion.java:57)
at recursionPrograms.recursion.buildWeirdString(recursion.java:57)
at recursionPrograms.recursion.main(recursion.java:25)