Reputation: 616
I'm working on a recursive method that will return and print in my main method, each letter of a string three backwards. The string being (args[1]). So for instance, if the string is "stack". It should output to:
kkkcccaaatttsss
So far I managed to print the string backwards. How should I go about printing each string three times?
My code so far:
public static void main(String[] args){
int number = Integer.parseInt(args[0]);
String word = new String("");
word = args[1];
String methodddd = recursive1.method4(word, number);
System.out.println(methodddd);
}
public static String method4(String word){
int length = word.length();
if (length == length*3){
return "";
}
return word.substring(length-1, length) + method4(word.substring(0, length-1));
}
Upvotes: 2
Views: 1892
Reputation: 112404
Here's the basic answer, in pseudocode:
recursive_stutter(s:string){
if length of s is 0
return
letter = s[0] // save the first character
recursive_stutter(s from 1 to length)
printf "%c%c%c",letter, letter, letter
}
Upvotes: 0
Reputation: 726929
You are very close: modify the return
line to pre-pend substring three times, instead of pre-pending it once:
public static String method4(String word){
int length = word.length();
if (length == 0){
return "";
}
String last = word.substring(length-1, length);
return last + last + last + method4(word.substring(0, length-1));
}
Note the ending condition: length == length*3
is true if (and only if) length
is zero.
Upvotes: 1