递归堆栈溢出错误Java

时间:2014-10-21 04:03:44

标签: java recursion

在尝试打印正整数n的前m个倍数时,递归方法中的堆栈溢出错误。我如何解决它?以下代码在逻辑上是正确的:

  import java.util.Scanner;
  public class Exercise3
  {
  public static void main (String args[])
  {
  Scanner keyboard = new Scanner(System.in);
  int n, m;
  System.out.println("Please enter values of n and m: ");
  n = keyboard.nextInt();
  m = keyboard.nextInt();
  // logic of code explained above
  for(int i = (m -(m - 1)); i <= m; i++)
  {
     System.out.print(multiple(n * i) + ",");
  }

  }
  // Now Write the Recursive method
  public static int multiple(int n)
  {
     if(n == 0)
        return 1;
      else 
       return multiple(n);
  }

}

3 个答案:

答案 0 :(得分:3)

这是一种非常糟糕的递归使用

public static int multiple(int n){ // once come into this method will never exit
  return multiple(n); // again and again call multiple
}

此递归方法没有退出条件。您需要考虑退出条件来终止此递归调用。

编辑:进行编辑:

public static int multiple(int n) { // inside this method n is never change
    if (n == 0)
        return 1;
    else
        return multiple(n);// still no termination for the recursion call      
}

答案 1 :(得分:3)

你可能想这样做:

for(int i = (m -(m - 1)); i <= m; i++)
    {
      System.out.print(multiple(n,i)+",");  // call like this in you main method
    }

这是递归函数:

 public static int multiple(int m,int n) {

        if (n == 1)
            return m;
        else
            return  m+multiple(m,n-1);


    }

答案 2 :(得分:0)

       import java.util.Scanner;
       public class Exercise3
       {
          public static void main (String args[])
          {
           Scanner keyboard = new Scanner(System.in);
             int n, m;
            System.out.println("Please enter values of n and m: ");
            n = keyboard.nextInt();
            m = keyboard.nextInt();
            // logic of code explained above
            for(int i = (m -(m - 1)); i <= m; i++)
            {
            System.out.print(n * i + ",");
            }
           }    

              }

//使用n = 2和m = 5来查看前5个的2的倍数。我需要一个递归方法来做同样的事情。这是迭代的