【发布时间】:2017-04-05 10:43:04
【问题描述】:
我需要编写一个printBackwards() 方法,使用三个预先给定的方法first、rest 和length。 printBackwards() 方法需要将 String 作为参数并在控制台上打印该字符串的每个字母,但每个字母都需要换行并以相反的顺序打印。所以如果字符串是House,输出应该是:
e
s
u
o
在这个练习中,我们应该使用递归和 if-else 语句。没有数组,没有其他(熟悉的)String 方法,没有 while 和 for 循环。
我做了一点,我知道这是不正确的,但这就是我设法做到的。我不明白如何编写代码,因此该方法可以在字母e 之前返回字母。 这里如何使用递归?
public class Recurse {
public static void main(String args[]){
System.out.println(printBackwards("House"));
}
//printBackward: takes a String as a parameter and prints letters of the String,
// one on each line, but backwards
public static String printBackwards(String s){
if (length(s) == 1){
return s;
} else {
return printBackwards(rest(s));
}
}
// first: returns the first character of the given String
public static char first(String s) {
return s.charAt(0);
}
// last: returns a new String that contains all but the
// first letter of the given String
public static String rest(String s) {
return s.substring(1, s.length());
}
// length: returns the length of the given String
public static int length(String s) {
return s.length();
}
}
【问题讨论】:
-
如果
printBackwards“在控制台上打印该字符串的每个字母”,它不需要返回任何东西 - 让它成为void。你可能想在某个地方打电话给first。
标签: java string recursion methods