我目前无法解决我的代码及其问题。我正在尝试创建一种通过递归和使用子字符串向后显示字符串的方法。例如,如果我把“10 ten”作为我的参数,它应该反转单词并重复字母 3 次。
它会像这样显示: nneeettt
这是我的方法的一部分,重点关注该部分。
public static String method3(Integer num,String line)
{
//base case
if (line.length() == 1)
//return line + line + line;
return line.substring(line.length()) + line.substring(line.length()) + line.substring(line.length());
//recursive case
else{
return method3(num,line.substring(1)) + line.charAt(0) + line.charAt(0) + line.charAt(0);
}
}//end of else
我的输出显示如下:
nnnee
还少了一个 “e”和最后 3 个“t”
编辑:
这是我的第二种方法,“10 ten”重复单词两次而不是三次并且不反转
public static String method2(Integer num, String line)
{
//base case
if(line.length() == 1)
return line + line;
//recursive case
else{
return line.substring(0,1) + line.substring(0,1)
+ method2(num,line.substring(1,line.length()));
}//end of else
}//end of method2
输出: 青少年
最佳答案
这是一种方法:
private static String reverse(String string) {
if(string.length() == 1)
return string + string + string;
else
return reverse(string.substring(1)) + string.charAt(0) + string.charAt(0) + string.charAt(0);
}
关于java - 使用递归和子字符串方法向后显示字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39552485/