简体   繁体   English

如何在Java中使用返回类型为void的递归方法?

[英]How to use a recursive method that has a return type void in java?

So I understand how to use a recursive method that has some other return type other than void. 因此,我了解如何使用具有除void以外的其他返回类型的递归方法。 Typically I would call the same method again in the same method( inside the recursive case), while decremented or increment some value in the call to reach the base case. 通常,我会在递归情况下的同一方法中再次调用同一方法,同时在调用中递减或递增一些值以达到基本情况。 Then at some point the base case is reached and the problem is solved, so it starts returning the value from every call. 然后在某个时候达到基本情况并解决了问题,因此它开始从每个调用返回值。 Along those lines. 遵循这些原则。

BUT
What if the method has the return type void, so you can't call the method as it won't/can't return anything? 如果该方法的返回类型为void,那么您将无法调用该方法,因为它不会/无法返回任何内容,该怎么办? I'm trying to write a sentence backwards, which I've solved both with a for loop and a resucrive method that can return a string value, but I'm not sure how to approach it if it's void which is what the assignment is asking for. 我正在尝试向后写一个句子,我已经用for循环和可以返回字符串值的递归方法解决了这两个问题,但是我不确定如果它是空的,那是如何分配的,所以我不确定要求。
Edit: I should also mention the sentence can only be passed in the parameter 编辑:我还应该提到该句子只能在参数中传递

Thank you everyone for the information and the help! 谢谢大家提供的信息和帮助!

Recursion doesn't work only with methods/functions that return values. 递归仅对返回值的方法/函数不起作用。 Recursion means only that the method/function calls itself. 递归仅意味着方法/函数调用自身。

You must guarantee that there is at least one stop condition but this does not require the function to return a value. 您必须保证至少有一个停止条件,但这不要求函数返回值。 This is commonly achieved by incrementally changing one or more arguments that you pass each time the function recursively calls itself. 通常,这是通过每次函数递归调用自身时递增地更改传递的一个或多个参数来实现的。 When that/those arguments satisfy a certain condition your function no longer calls itself and all pending operations are solved. 当那些参数满足特定条件时,您的函数将不再调用自身,并且所有待处理的操作都将得到解决。

I am not fully aware of the task you are trying to do but here is an example of a recursive function that writes a string backwards. 我不完全了解您要执行的任务,但是这里有一个递归函数的示例,该函数向后写一个字符串。 I use PSEUDO-functions with names that hopefully are self-explanatory. 我使用PSEUDO函数,其名称希望是不言自明的。

public void writeBackwards(String str) {
    // This is the negation of the stop condition, so the stop condition
    // is when the string is empty, in which case this function will do
    // nothing:
    if (!str.isEmpty()) {
        char firstCharacter = str.getFirstCharacter();
        str = str.removeFirstCharacter();
        writeBackwards(str); // the recursive call
        // The following operation will be pending, waiting for the
        // recursive call to be resolved first:
        writeCharacter(firstCharacter);
    }
}

You can use any mutable Object as a parameter of the recursive function to store the result. 您可以使用任何可变对象作为递归函数的参数来存储结果。 For example, the backwards-sentence problem you mentioned could be written as: 例如,您提到的向后句问题可以写为:

public void stringReverse(String s, int index, StringBuilder sb) {
    if (index < 0)
        return;
    sb.append(s.charAt(index));
    stringReverse(s, index - 1, sb);
}

And called like this 叫这样

StringBuilder sb = new StringBuilder();
stringReverse(mySentence, mySentence.length() - 1, sb);

Just like in C++ you can pass in pointers, here in Java you can simply pass in a class object to your function to hold the value generated from the recursive calls of the function. 就像在C ++中一样,您可以传递指针,而在Java中,您可以简单地将类对象传递给函数,以保存从函数的递归调用生成的值。 A simple example reflecting your question to compute fibonacci number is following. 下面是一个反映您的问题以计算斐波那契数的简单示例。

public class ComputeFibonacci {
  static class Fibonacci {
    public int ith;
    public int value;
    Fibonacci(int a, int b) {
      ith = a;
      value = b;
    }
  }

  private static void fibonacci(Fibonacci result) {
    if (result.ith == 1 || result.ith == 2) {
      result.value = 1;
    } else {
      Fibonacci left = new Fibonacci(result.ith - 1, 0);
      Fibonacci right = new Fibonacci(result.ith - 2, 0);
      fibonacci(left);
      fibonacci(right);
      result.value = left.value + right.value;
    }
  }

  public static void main(String[] args) {
    // Here we compute the 10th fibonacci number
    Fibonacci f = new Fibonacci(10, 0);
    fibonacci(f);
    System.out.println("The result is " + f.value);
  }
}

Good luck. 祝好运。

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

相关问题 Java中返回类型为void的方法中返回的意义 - Significance of return in the method with return type as void in Java 如何将Java 8可选API用于返回void的方法调用 - How to use Java 8 optional API for method calls that return void 在具有返回类型的方法中,return语句是可选的,它不是无效的,但会引发异常? - Is return statement optional in a method that has return type not void, but throws an Exception? 如何更改void方法以在Java中返回值 - How to change a void method to return a value in Java 如何使用Java泛型来列出 <InterfaceImpl> 可以为具有返回类型List的方法返回 <Interface> - How to use Java Generics so that List<InterfaceImpl> can be returned for a method that has return type List<Interface> 如何使用带有void返回类型的Callable? - How to use Callable with void return type? 在Java中,如果递归方法可以返回混合值,我应该如何声明返回类型? - In Java, how should I declare the return type if a recursive method can return mixed values? java-从另一个类返回无效类型的调用方法 - java - invoke method with void return type from another class 为什么不能使用Void作为main方法的返回类型 - Why can't use Void as the return type for main method 如何在 Java Reactor 链中使用 void 方法? - How to use a void method in a Java Reactor chain?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM