-2

I am trying to write a recursive method to print n number of asteriks in a line and create a new line at the end.

So, TriangleOps.line(5);

would print

    *****

This is the code I wrote:

    public static void line (int n){
    if(n>0){
    System.out.println("*");
    line(n-1);
    }}

instead it prints

    *
    *
    *
    *
    *

with a lot of space at the end. Can anyone tell me how to remove the line breaks?

  • 2
    `println` prints a newline: use `System.out.print`, and then a `println` at the base case to get the newline – pb2q Oct 14 '12 at 03:33

3 Answers3

2

Use

System.out.print();

instead

println(); method adds new line character at the end by it self

jmj
  • 237,923
  • 42
  • 401
  • 438
2

Modify the println to print and add a println at the end:

public static void line(int n) {
    if (n > 0) {
        System.out.print("*");
        line(n - 1);
    }
    System.out.println();
}
Welsh
  • 5,138
  • 3
  • 29
  • 43
1

Type System.out.print(); to overwrite

println(); by doing this the method adds new line character at the end by itself