Search code examples
javafor-loopoutputseparator

Java custom separator output for looping


I've this for loop

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

and i want an output like this (if bil =5)

1, 3 and 5

So, how to get this output that have a comma separator and the last loop have different separator like 'and' ?


Solution

  • Here is one way of doing it:

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

    Results with various values of 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