Java For 循环到递归函数中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5882242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:16:32  来源:igfitidea点击:

Java For Loop into Recursive function

javarecursionfor-loopwhile-loop

提问by Paradox

public class For {
 public static void main(String[] args){
          for(int i=2; i<=1024; i *= 2){
           System.out.println("Count is: " + i);
      }
 }




public class While {
    public static void main(String[] args){
        int i = 1;
        while (i < 1024) {
            i *= 2;
            System.out.println("Count is: " + i);
      }
 }


public class DoWhile {
     public static void main(String[] args){
        int i = 1;
        if (i < 1024) {
            do { i*=2;
                System.out.println("Count is: " + i);
            } while (i < 1024);
        }
     }

How would one convert the for loop/while loop so it does the same thing, but using a recursive function?

如何转换 for 循环/while 循环,使其做同样的事情,但使用递归函数?

回答by David Grant

Like so:

像这样:

public class Recursive {
    public void r(int i) {
        if (i < 1024) {
            i *= 2;
            System.out.println("Count is: " + i);
            r(i);
        }
    }

    public static void main(String[] args) {
        Recursive r = new Recursive();
        r.r(1);
    }
}

回答by Fred Foo

Take the loop of mainand put it in its own function with an argument int i. In that function, rewrite the loop to

取循环main并将其放入自己的带有参数的函数中int i。在该函数中,将循环重写为

  1. If the loop condition is false (i >= 1024), then return
  2. Else, recursive call with argument i*2.
  1. 如果循环条件为假 ( i >= 1024),则return
  2. 否则,递归调用参数i*2

Call the function with argument 1or 2, depending on which of your programs you're rewriting (they don't entirely match).

使用参数1or调用函数2,具体取决于您要重写的程序(它们不完全匹配)。

回答by Lukasz

Recurrent loop can look like this:

循环循环可以是这样的:

class Main
{
    public static void main(String[] args){
      RecWhile(1);
    }

    public static void RecWhile(int i) {
       if (i < 1024) {
         i = i*2;
         System.out.println("Count is: " + i);
         RecWhile(i);
       }
    }
}

回答by satish hiremath

public class Test1 {

公共类 Test1 {

public static void main(String[] args) {

    Test1 mainFunc = new Test1();

    int[] arr = {1,2,4,3,5,6};

    int start=0;
    int end=arr.length;
    mainFunc.callRecursiveFun(start, end, arr);
}

public int callRecursiveFun(int start, int end, int[] arr) {
    int arrLen = end;
    if(arrLen == 0) {
        return 0;
    } else {

    System.out.println("Loop Index at "+start +": "+arr[start]);


    }
    return callRecursiveFun(start+1, end-1, arr);
}

}

}