如何摆脱循环中的尾随逗号?

时间:2017-11-08 02:19:28

标签: loops

如何摆脱此循环中的尾随逗号?

    outStream.print(" float on lines: ");
    for(int j = 0; j < intLines.length; j++){      
        totalFloats = totalFloats + floatLines[j];

        if(floatLines[j] > 0){
            outStream.printf("%d, ", floatLines[j]);
        }
    }
    if(totalFloats == 0){
        outStream.print("none");
    }
    outStream.println();

1 个答案:

答案 0 :(得分:1)

只需添加一个最终循环检查,如果它是最后一个循环,只需使用outStream.printf("%d ", floatLines[j]);

示例:

outStream.print(" float on lines: ");
string separator = "%d";
for(int j = 0; j < intLines.length; j++){      
    totalFloats = totalFloats + floatLines[j];

    if (j != 0 && floatLines[j] > 0)
    {
       separator = ", %d";
    }    
    if(floatLines[j] > 0){
         outStream.printf(separator, floatLines[j]);
    } 

}
if(totalFloats == 0){
    outStream.print("none");
}
outStream.println();