仅在值之间使用分隔符打印 [英] Printing with delimiter only between values

查看:22
本文介绍了仅在值之间使用分隔符打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码输出有一个小问题,我一直在寻找与此相同的主题,但我没有找到.

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

输出必须是.每当我输入整数.例如 5.

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

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

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

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

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

推荐答案

StringJoiner

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

有了这个,你可以给出一个分隔符、前缀和后缀,然后只需添加你的所有元素,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);

这篇关于仅在值之间使用分隔符打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆