Reputation: 11
How can I make this code a recursive method?
for (int i = 3; i < arr.length; i++) {
writer.write(arr[i] + "\n");
strout += arr[i] + "\n";
}
Upvotes: 0
Views: 118
Reputation: 168
You can try encapsulating the code in a function:
public static String printRecursive(BufferedWriter writer, String[] arr, int i) throws IOException {
String strout = "";
if(i<arr.length) {
writer.write(arr[i] + "\n");
//System.out.println(arr[i] + "\n");
strout += arr[i] + "\n" + printRecursive(writer,arr,i+1);
}
return strout;
}
And you can call it from main:
String strRec = printRecursive(writer,arr,3);
I hope this help you.
Edited: Added writer according last comment
Upvotes: 2
Reputation: 3156
Something like that?
let arr = [/* array elements */];
let idx = 3;
let stdout = "";
const recursiveMethod = () => {
writer.write(`${arr[idx]}\n`);
strout += `${arr[idx]}\n`;
if(idx < arr.length) {
idx++;
return recursiveMethod();
}
}
recursiveMethod();
Upvotes: 0