If 语句有助于何时使用逗号和空格

If statement help on when to use commas and spaces

基本上我已经构建了一个字符串,我需要在何时使用逗号和 space 上放置一个 if 语句。所以基本上我需要它在第一个元素之后而不是在最后一个元素上。

这是我当前的代码:

它的输出returns是

"thing1thing2thing3"

我想让输出为

"thing1, thing2, thing3"

我需要一个 if 语句作为何时放置逗号和 space 的要求的一部分。

提前致谢。

这对您来说可能有点高级,但使用 Java 8 时非常容易(如果 thingsCollection:

return Optional.of(things.stream()
                         .filter(thing -> thing.getCategory() == things.STUFF)
                         .collect(Collectors.joining(", ")))
               .orElse("nothing");

如果您使用的是 Java 7,那么您可以手动完成:

StringBuilder sb = new StringBuilder();

for (Thing thing : things) {
    if (things.getCategory() == some.STUFF){
        sb.append(thing.getName()).append(", ");
    }
}

if (s.isEmpty()) {
    return "nothing";
}

return sb.delete(sb.length() - 2, sb.length()).toString();

题目中有一些不清楚的地方,所以下面的代码是基于我目前所理解的。

String s = "";
boolean isComma = true; // true = comma, false = space.
for (Thing thing : things)
{
    if (things.getCategory() == thing.STUFF)
    {
        //Check if there already exists an entry within the String.
        if (s.length() > 0)
        {
            //Add comma or space as required based on the isComma boolean.
            if (isComma)
            {
                s += ", ";
            }
            else
            {
                s += " ";
            }
        }
        s += thing.getName();
    }
}

if (s.equals(""))
{
    s += "nothing";
}
return s;

我会使用 for 循环而不是 for-each 循环——只是因为我认为它不需要额外的计数器变量。这就是我处理问题的方式。

    String[] things = {"thing 1", "thing 2", "thing 3", "thing 4"};

    for(int i = 0; i < things.length; i++)
    {
        if(i < things.length - 1)
        {
            System.out.print(things[i] + ", ");
        }
        else
        {
            System.out.print(things[i] + ".");
        }
    }