如何摆脱此循环中的尾随逗号?
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();
答案 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();