Reputation: 167
I'm working a problem on recursion. After writing the code requested, the site I'm working from runs the code with different values as input. However, the first run works properly, but all subsequent runs concatenate the return value of the first run with the values of each of the subsequent runs.
I am also getting a stack overflow error at the end.
I need help!
Here is the code:
package com.company;
import static java.lang.System.*;
public class Main {
public static String returnValue="";
public static void main(String[] args) {
repeat("this is fun", 1);
out.println(returnValue);
}
public static String repeat(String s, int i){
if (i==0) {
return returnValue;
}
else{
returnValue+=s;
repeat(s,i-1);
}
return returnValue;
}
}
Any help is greatly appreciated.
Upvotes: 0
Views: 32
Reputation: 1519
If you are comfortable with expressions:
public static String repeat(String s, int i) {
return i <= 0
? ""
: s + repeat(s, i - 1);
}
and you can get rid of the static attribute!
Upvotes: 0
Reputation: 65811
You need to move the static returnValue
into the method. You then need to control the result by capturing the string returned by the inner recursive call.
Something like:
public static String repeat(String s, int i){
String returnValue="";
if (i==0) {
return returnValue;
}
else{
returnValue+=s + repeat(s,i-1);
}
return returnValue;
}
NB: This may not be the equivalent algorithm to what you intend but it should demonstrate the technique.
If that is the correct solution then you can tidy up with:
public static String repeat(String s, int i){
if (i==0) {
return "";
} else {
return s + repeat(s,i-1);
}
}
Upvotes: 1