onetwenty8k
2[H]4U
- Joined
- Nov 24, 2006
- Messages
- 2,554
I have a question this week in CS that is giving me trouble. We have to write two recursive methods, one that takes a string and prints it back with each letter separated by a comma and a space, and the other does the same thing but in reverse. I think I understand recursion but I kinda took a shortcut for the first problem and thus, the second gives me trouble. Any tips for solving are appreciated. Here is what I have.
Code:
public static void printLetters(String str) {
if (str == null || str.equals("")) {
return;
}
if (str.length() != 1) {
System.out.print(str.charAt(0) + ", ");
printLetters(str.substring(1));
} else
System.out.print(str.charAt(0));
}
public static void printLettersReverse(String str) {
if (str == null || str.equals(""))
return;
if (str.length() >= 1) {
printLettersReverse(str.substring(1));
//and stuck
}