Java Recursion: How to avoid the last comma when write 1..n seperated by commas in one line. See full task description inside

Viewed 184

I have the following task:

Write a recursive void method that takes a single (positive) int argument n and writes the integers 1, 2, . . . , n to the screen.

What I tried so far is:

public static void write1ToNInOneLine(int n){
    if (n == 0) {
        return;
    } 
    else // n is two or more digits long:
    {
        write1ToNInOneLine(n - 1);
        System.out.print(n + ",");
    }
}

but obviously I have the last redundant comma on output.

Is there a way to avoid it?

3 Answers

The problem with your code:

public static void write1ToNInOneLine(int n){
    if (n == 0) {
        return;
    } 
    else // n is two or more digits long:
    {
        write1ToNInOneLine(n - 1);
        System.out.print(n + ",");
    }
}

is that you are not handling the end-case correctly.

single (positive) int argument n and writes the integers 1, 2, . . . , n to the screen.

In your case, the end-case is when the n = 1. Moreover, you are doing System.out.print(n + ","); which means that the after the last element you will add ",". Because the end case is "1" it is better to do System.out.print(","+ n); so that the last element (i.e., n = n) will not have ",", and handle the case when n = 1 so that you do not add "," before 1. Like as follows:

public static void write1ToNInOneLine(int n){
    if (n == 1){
        System.out.print(n);
    }
    else if (n > 1){
        write1ToNInOneLine(n - 1);
        System.out.print(","+ n);
    }
}

Output:

1,2,3,4,5,6,7,8,9,10

Alternatively:

public static String write1ToNInOneLine(final int n) {
    return ((n > 1) ? write1ToNInOneLine(n - 1) + "," : "") + n;
}

and then:

System.out.println(write1ToNInOneLine(10));

Looks like there are already some other answers here, but just to show that there can be many different ways to achieve the same output, a slightly different and more concise version could be something like:

public static void write1ToNInOneLine(final int n) {
    if(n > 1)
    {
        write1ToNInOneLine(n - 1);
        System.out.print(',');
    }
    System.out.print(n);
}

When called like so: write1ToNInOneLine(6), the output is:

1,2,3,4,5,6

The least code that I can get to achieve this is:

public static void write1ToNInTwoLines(int i) {
    if (i > 1) write1ToNInOneLine(i-1);
    System.out.print(i > 1? "," + i : i);
}

This has a couple of benefits that I can see:

  • it is completely self contained (return type void) - the caller does not have to print
  • it does exactly what it needs to and only that (e.g. no use empty speech-marks "")

to call you invoke:

write1ToNInTwoLines(10);

and will print:

1,2,3,4,5,6,7,8,9,10

Related