仅在值之间使用分隔符打印

Printing with delimiter only between values

我的代码输出有点问题,一直在搜索与此相同的主题,但我没有找到。

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("");
}

输出一定是。每当我输入整数时。例如 5.

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

但小问题是输出是这样的5! = 1 x 2 x 3 x 4 x 5 x

最后一个数字上有多余的 x 不应该存在

替换此行:

System.out.printf("%d x " ,i);

通过这个:

if (i == n)
   System.out.printf("%d" ,i);
else
   System.out.printf("%d x " ,i);

这样就可以避免在打印因式分解中的最后一个数字时打印“x”。

也许你可以这样做:

while (true) {
    System.out.print("Enter a positive integer: ");    
    n = sc.nextInt();
   
    String result = "";
    System.out.print(n + "! = ");
    for (int i = 1; i <= n; i++) {
        factorial = factorial * i;
        result += i + " x ";
    }
    System.out.println(result.substring(0, result.length() - 3);
}

字符串连接器

其他人已经回答了如何修复您的代码,但我想为您提供更专业的解决方案,即使用StringJoiner.

有了这个,你可以给出一个分隔符、前缀和后缀,然后只需添加你所有的元素,StringJoiner 将确保分隔符只添加在它们之间。它需要你的所有工作。这是代码:

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

如果您更喜欢直播:

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