【问题标题】:How to use a recursive method that has a return type void in java?java - 如何在java中使用返回类型为void的递归方法?
【发布时间】:2016-02-28 22:08:49
【问题描述】:

所以我了解如何使用具有除 void 之外的其他返回类型的递归方法。通常我会在相同的方法中再次调用相同的方法(在递归情况下),同时在调用中减少或增加一些值以达到基本情况。然后在某个时候达到了基本情况并解决了问题,因此它开始从每次调用中返回值。沿着这些思路。

但是
如果该方法的返回类型为 void,那么您不能调用该方法,因为它不会/不能返回任何东西?我正在尝试向后写一个句子,我已经用一个 for 循环和一个可以返回字符串值的 resucrive 方法解决了这个问题,但我不知道如果它是 void 是什么赋值是如何处理它求。
编辑:我还应该提到这句话只能在参数中传递

感谢大家提供的信息和帮助!

【问题讨论】:

  • 使用类级别对象来保存递归数据。但是不好的做法是因为很难跟踪递归问题/实际上很难实现递归,因为您的对象一直在变化。主要用于简单的情况,如求和/连接。

标签: java recursion


【解决方案1】:

递归不仅仅适用于返回值的方法/函数。递归仅意味着方法/函数调用自身。

您必须保证至少有一个停止条件,但这并不要求函数返回值。这通常通过在每次函数递归调用自身时递增地更改您传递的一个或多个参数来实现。当那个/那些参数满足某个条件时,您的函数将不再调用自身,并且所有未决操作都将得到解决。

我不完全了解您正在尝试执行的任务,但这里是一个向后写入字符串的递归函数的示例。我使用 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);
    }
}

【讨论】:

  • 谢谢。我想我太专注于它需要实际返回一些东西。我最终使用一个变量作为一个角色的空间持有者。它将从最后一个位置一直打印该字符,直到到达字符位置 0 的基本情况。所以变量将是最后一个字符,打印该变量,然后再次调用该函数减去 1 个位置。我看了以前的例子,看起来很复杂,但这很简单。
【解决方案2】:

您可以使用任何可变对象作为递归函数的参数来存储结果。比如你提到的倒车问题可以写成:

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

这样称呼

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

【讨论】:

    【解决方案3】:

    就像在 C++ 中你可以传递指针一样,在 Java 中你可以简单地将一个类对象传递给你的函数来保存函数递归调用生成的值。下面是一个反映您计算斐波那契数的问题的简单示例。

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

    祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-02
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多