简体   繁体   English

Java-突破入侵方法并返回值

[英]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 这使我感到困惑,因为它在n <1之后确实有一个返回值(来自Stringbuilder的总字符串)

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);
            }
        }
    }

if(n < 1) {return full.toString();} but if n >= 1 you don't return anything. if(n < 1) {return full.toString();}但如果n> = 1,则不返回任何内容。 It should be return repeat(str, n - 1); 它应该是return repeat(str, n - 1); but then you need to move the for... part 但是然后您需要移动for...部分

The immediate cause of your problem is that not all conditional flows in your repeat() method have a return value. 问题的直接原因是,并非repeat()方法中的所有条件流都具有返回值。 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. 在这里,我们传入一个StringBuilder对象,该对象要包含重复的字符串结果。 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循环:

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). 这看起来不是递归的,循环重复添加字符串会破坏执行递归的点(尽管如果必须这样做,我可能会在现实生活中使用循环)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM