[英]Code returns Stack overflow error in Java recursion
This code is returning stack overflow error, what do I do?此代码返回堆栈溢出错误,我该怎么办?
/* package whatever; // don't place package name! */
import java.io.*;
class myCode
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
System.out.println(printStar(Integer.parseInt(input)));
}
private static int printStar(int n){
if(n > 0){
System.out.print("\n hello");
}
return printStar(n-1);
}
}
Let's say you type in the number 2.假设您输入数字 2。
1st call: printStar(2)
.第一次调用:
printStar(2)
。 Prints hello
and calls printStar(1)
.打印
hello
并调用printStar(1)
。
2nd call: printStar(1)
.第二次调用:
printStar(1)
。 Prints hello
and calls printStar(0)
.打印
hello
并调用printStar(0)
。
3rd call: printStar(0)
.第三次调用:
printStar(0)
。 Doesn't print anything, because n > 0
is false.不打印任何内容,因为
n > 0
是假的。 But , still calls printStar(-1)
.但是,仍然调用
printStar(-1)
。
Your code is calling the next step independently of the value of n.您的代码独立于 n 的值调用下一步。 In my understanding of what you want to achieve, your recursive call should be inside the
if
block.根据我对您想要实现的目标的理解,您的递归调用应该在
if
块内。 If n > 0
returns false, just return something else, like -1
.如果
n > 0
返回 false,则返回其他内容,例如-1
。
The code would look like this:代码如下所示:
private static int printStar(int n) {
if (n > 0) {
System.out.print("\n hello");
return printStar(n - 1);
}
return -1;
}
I have to point, though, that I'm not sure if printStar
returning a value is a good idea.不过,我必须指出,我不确定
printStar
返回一个值是否是一个好主意。 The returned value will always be the same.返回的值将始终相同。 You can change the method to
void
.您可以将该方法更改为
void
。 Your whole code would look like this:您的整个代码如下所示:
public static void main(String[] args) throws java.lang.Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
printStar(Integer.parseInt(input));
}
private static void printStar(int n) {
if (n > 0) {
System.out.print("\n hello");
printStar(n - 1);
}
}
您的printStar函数将永远持续下去,因为即使n达到 0 或更低,您也不会停止递归函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.