MrEmper
MrEmper

Reputation: 235

Java - breaking out of a incursion method and returning the value

Good morning all,

Today is my first time trying to make a recursion method. Just when I thought it would work I got the error; missing return statement. This confuses me because it literally has a return value ( the total string from the Stringbuilder ) after n < 1

This is what I got:

    import java.util.Scanner;

    public class P5_4MethodRepeatString {
        public void main(String[] args){

            Scanner sc = new Scanner(System.in);
            System.out.println("Enter a string followed by the times you want 
            it repeated:");
            String input = sc.nextLine();
            int count = sc.nextInt();

            String total = repeat(input, count);

            System.out.println(total);
        }

        public static String repeat(String str, int n) {
            StringBuilder full = new StringBuilder();
            if(n < 1) {return full.toString();}
            repeat(str, n - 1);
            for(int i = 0; i < n; i++){
                full.append(str);
            }
        }
    }

Upvotes: 0

Views: 227

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

The immediate cause of your problem is that not all conditional flows in your repeat() method have a return value. But I am not sure if even making that change would result in working code. Consider the following refactor:

public void repeat(StringBuilder result, String str, int n) {
    if (n == 0) return;
    result.append(str);
    repeat(result, str, n - 1);
    return;
}

Here we are passing in a StringBuilder object which we want to contain our repeated string results. We also pass the string to be repeated, and the number of remaining turns. The base case occurs where there are no more turns, in which case we simply return from the recursive method. Otherwise, we add one copy of the string and make a recursive call.

Your original recursive attempt had the following for loop:

for (int i=0; i < n; i++) {
    full.append(str);
}

This does not look recursive, and looping to repeatedly add the string defeats the point of doing recursion (though I would probably use a loop in real life if I had to do this).

Upvotes: 1

Lance Toth
Lance Toth

Reputation: 440

if(n < 1) {return full.toString();} but if n >= 1 you don't return anything. It should be return repeat(str, n - 1); but then you need to move the for... part

Upvotes: 2

Related Questions