Search code examples
javastringstring-concatenation

Printing with delimiter only between values


I have a slight problem with the output of my code and been searching for such topics same as with this but I don't find any.

while (true) {
    System.out.print("Enter a positive integer: ");    
    n = sc.nextInt();
    
    System.out.print(n + "! = ");
    for (int i = 1; i <= n; i++) {
        factorial = factorial * i;
        System.out.printf("%d x " , i);
    }
    System.out.println("");
}

The output must be. Whenever I type integer. e.g 5.

Enter a positive integer: 5
5! = 1 x 2 x 3 x 4 x 5

But the slight problem is that the output goes like this 5! = 1 x 2 x 3 x 4 x 5 x

There's extra x on the last number which should not be there


Solution

  • StringJoiner

    Others already answered how to fix your code but I would like to provide you with a more professional solution, namely by using a StringJoiner.

    With this, you can give a delimiter, prefix and suffix, then just add all your elements and the StringJoiner will make sure that the delimiter is only added in between. It takes all the work from you. Here is the code:

    StringJoiner sj = new StringJoiner("x ", n + "! = ", "");
    for (int i = 1; i <= n; i++) {
        sj.add(Integer.toString(i));
    }
    System.out.println(sj);
    

    Streams

    If you prefer streams:

    String result = IntStream.rangeClosed(1, n)
        .mapToObj(Integer::toString)
        .collect(Collectors.joining("x ", n + "! = ", ""));
    System.out.println(result);