: An array containting strings of actual written code needs to be formatted. I'm not sure how to even recursively call a method so it prints the contents of an array, let alone format it's text. Not sure if I even put my methods together properly. The code only prints the first index value of the array, no recursion takes place, and the counter variable value isn't increasing. How do I recursively call the method? Can anyone help?
:
: public static void indent(String[] code){
:
: int counter = 0;
: String spaces = " ";
:
: System.out.print(indent(code, counter++, spaces));
: }
:
: public static String indent(String[] code, int counter, String spaces){
:
: String tmpStr1,
: tmpStr2;
:
: if(counter == 0){
: return code[counter];
: }
:
: tmpStr1 = code[counter - 1];
: tmpStr2 = code[counter];
:
: if(tmpStr1.charAt(tmpStr1.length() - 1) == '{' && counter < code.length - 1){
: code[counter] = spaces + tmpStr2;
: }
:
: return code[counter];
:
: }
:
: }
:
Recursions and arrays is quite simple. A recursive function calls itself until a certain condition is met. In case of an array the condition is nearly always the end of the array. In pseudo-code it looks something like this:
recurseExample(Array a, int counter) {
if (counter < a.length) {
Do something with a[counter]
recurseExample(a, counter++); // recursiveness
} else {
// a[counter] is invalid, since counter >= a.length
}
}
This example "walks" through the array from some point to the end. For example:
recurseExample(a, 2);
processes the array from the third element to the last.
The statement "Do something with a[counter]" can be calls to another method, which performs the processing, or it can be code included in the if-then statement.
Here is a full working example of a recursive function:
int recursiveSum(int[] numbers, int index) {
int result;
if (index < numbers.length) {
result = numbers[index]; // processing
result = result + recursiveSum(numbers, index++); // recursive call
} else {
result = 0
}
return result;
}