Java 用于循环的自定义分隔符输出

Java custom separator output for looping

我有这个 for 循环

for(int i=1; i <= bil; i++){
            if (i%2!=0)
            System.out.print(i+" ");
        }

我想要这样的输出(如果 bil =5)

1, 3 and 5

那么,如何获得具有逗号分隔符的输出,而最后一个循环具有不同的分隔符,如 'and'?

这是一种方法:

StringBuilder buf = new StringBuilder();
int lastComma = 0;
for (int i = 1; i <= bil; i++) {
    if (i % 2 != 0) {
        if (buf.length() != 0) {
            lastComma = buf.length();
            buf.append(", ");
        }
        buf.append(i);
    }
}
if (lastComma != 0)
    buf.replace(lastComma, lastComma + 1, " and");
System.out.print(buf.toString());

bil

各种值的结果
bil=1   ->  1
bil=2   ->  1
bil=3   ->  1 and 3
bil=4   ->  1 and 3
bil=5   ->  1, 3 and 5
bil=6   ->  1, 3 and 5
bil=7   ->  1, 3, 5 and 7
bil=8   ->  1, 3, 5 and 7
bil=9   ->  1, 3, 5, 7 and 9
bil=10  ->  1, 3, 5, 7 and 9

试试这个。

static void printBil(int bil) {
    String separator = "";
    for (int i = 1; i <= bil; i++) {
        if (i % 2 != 0)
            System.out.print(separator + i);
        separator = i + 2 >= bil ? " and " : ", ";
    }
    System.out.println();
}

for (int i = 1; i < 10; ++i) {
    System.out.print("bil=" + i + " : ");
    printBil(i);
}

输出:

bil=1 : 1
bil=2 : 1
bil=3 : 1 and 3
bil=4 : 1 and 3
bil=5 : 1, 3 and 5
bil=6 : 1, 3 and 5
bil=7 : 1, 3, 5 and 7
bil=8 : 1, 3, 5 and 7
bil=9 : 1, 3, 5, 7 and 9

试试。

var sj = new StringJoiner(", ", "", "");
String tmp = null;
for (int i = 1; i <= bil; i++) {
    if (i % 2 != 0) {
        if (tmp != null) {
            sj.add(tmp);
        }
        tmp = Integer.toString(i);
    }
}
var res = sj.length() > 0
        ? sj.toString() + " and " + tmp
        : sj.add(tmp).toString();
System.out.println(res);

结果:

bil=1   ➡️  1
bil=2   ➡️  1
bil=3   ➡️  1 and 3
bil=4   ➡️  1 and 3
bil=5   ➡️  1, 3 and 5
bil=6   ➡️  1, 3 and 5
bil=7   ➡️  1, 3, 5 and 7
bil=8   ➡️  1, 3, 5 and 7
bil=9   ➡️  1, 3, 5, 7 and 9
bil=10  ➡️  1, 3, 5, 7 and 9