[英]Recursion Stack Overflow Error Java
Stack Overflow Error in Recursion Method when trying to print the first m multiples of a positive integer n. 尝试打印正整数n的前m倍时,递归方法中的堆栈溢出错误。 How do I fix it?
我如何解决它? Code below is already logically correct:
以下代码在逻辑上已经正确:
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);
}
} }
This is a very bad use of recursion 这是非常不好的递归用法
public static int multiple(int n){ // once come into this method will never exit
return multiple(n); // again and again call multiple
}
There is no exit condition from this recursion method. 此递归方法没有退出条件。 You need to think about an exit condition to terminate this recursive call.
您需要考虑退出条件以终止此递归调用。
Edit: for your edit: 编辑:用于您的编辑:
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
}
you probably want to do this: 您可能想这样做:
for(int i = (m -(m - 1)); i <= m; i++)
{
System.out.print(multiple(n,i)+","); // call like this in you main method
}
This is recursive function : 这是递归函数:
public static int multiple(int m,int n) {
if (n == 1)
return m;
else
return m+multiple(m,n-1);
}
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 + ",");
}
}
}
// Use n = 2 and m = 5 to see first 5 multiples of 2. I need a recursive method to do the same thing. //使用n = 2和m = 5来查看2的前5个倍数。我需要递归方法来执行相同的操作。 This is iterative
这是迭代的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.