java - 在递归方法中有一个变量在每次调用后都不会重新定义自己

标签 java recursion

我将在下面发布我的代码,因为这有点难以描述。下面的代码有效,但它在 main 方法中而不是在 helper 中使用 Math.pow,所以如果有人能告诉我一种方法将权力转移到 helper 方法而不弄乱程序,我将不胜感激。

主要方法:

  Scanner keyboard = new Scanner(System.in);

  System.out.println("Please enter an integer: ");
  double input = keyboard.nextInt();

  double x = Math.pow(2.0, input);
  int n = (int)x;

  System.out.println(starStr(n));

辅助方法:

  public static String starStr(int n)
  {     
     if (n >= 1) {
        return ("*" + starStr(n-1));
     }
     else {
        return "";
     }
  }

编辑:

 if(n == 0) {
     return "*";
  }   
  else {
     return starStr(n - 1) + "**";
  }

最佳答案

像这样的东西会起作用。你根本不需要使用幂函数。只需从 1 星开始,然后在递归的每一步中将星数加倍。

public static void main(String[] args) {

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Please enter an integer for the number of stars: ");
    int input = keyboard.nextInt();

    System.out.println(doStars(input));
}

public static String doStars(int n)
{
    //If n == 0 the recursion is done
    //Otherwise, reduce n by 1 and double the number of stars
    if(n == 0)
        return "*";
    else
    {
        String output = doStars(n - 1);
        return output + output;
    }
}

关于java - 在递归方法中有一个变量在每次调用后都不会重新定义自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33287626/

相关文章:

Java - 如何遍历 3 维 ArrayList?

java - 如何在java中执行vbs文件,哪个目录包含空格

java - 是否可以在 Netbeans 的项目 View 中显示一个类是公共(public)类还是包私有(private)类?

recursion - 用于嵌套循环的 Lisp 宏(或函数)

java - Android 当应用程序未在后台运行时发送短信

java - eclipse 重构插件

php - 递归嵌套对象

algorithm - 寻找树的深度?

recursion - sed:将保持空间与模式空间相匹配

c++ - Qt C++ QDomDocument,递归迭代 XML 数据,检索没有子数据的文本元素