Code returns Stack overflow error in Java recursion

ken4ward :

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

  }

}
Mateus Bandeira :

Let's say you type in the number 2.

1st call: printStar(2). Prints hello and calls printStar(1).

2nd call: printStar(1). Prints hello and calls printStar(0).

3rd call: printStar(0). Doesn't print anything, because n > 0 is false. But, still calls printStar(-1).

Your code is calling the next step independently of the value of n. In my understanding of what you want to achieve, your recursive call should be inside the if block. If n > 0 returns false, just return something else, like -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. The returned value will always be the same. You can change the method to 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);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27181&siteId=1