public static void main(String[] args) {
PrintAsteriskLine(5);
System.out.println("Separate");
PrintAsterisk(7);
}
public static void PrintAsterisk(int N)
{
if (N==1)
PrintAsteriskLine(N);
else
PrintAsteriskLine(N);
PrintAsterisk(N-1);
}// end PrintAsterisk
public static void PrintAsteriskLine(int N)
{
if (N==1)
System.out.println("*");
else
{
System.out.print("*");
PrintAsteriskLine(N-1);
}
} // end PrintAsteriskLine
Above is my code in Java. I'm coding on NetBeans. The idea was to nest the PrintAsteriskLine function inside the PrintAsterisk function to print N number of lines of asterisks, starting at N and incrementing towards 1. For an example, if I input 3 as an argument, then the following would be the output:
***
**
*
Now, my code does do that. However, it also gives me a stack overflow error that I don't understand. Can someone explain to me what is happening? Is it because I'm nesting recursive functions? I really am at a loss. It works but gives me an error message :/
Exception in thread "main" java.lang.StackOverflowError at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:691) at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:579) at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:271) at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125) at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207) at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129) at java.io.PrintStream.write(PrintStream.java:526) at java.io.PrintStream.print(PrintStream.java:669) at madisonbrewerrecursion.MadisonBrewerRecursion.PrintAsteriskLine(MadisonBrewerRecursion.java:38)
Then it says
at madisonbrewerrecursion.MadisonBrewerRecursion.PrintAsteriskLine(MadisonBrewerRecursion.java:39)
A whole bunch of times. Line 38 is the print statement in PrintAsteriskLine and 39 is the clone-call/incrementation. So, as far as I can see it has a problem with my PrintAsteriskLine function, which works fine when called on its own, though.