如何在不添加尾随逗号的情况下用逗号连接一堆数字?

时间:2011-03-28 18:56:24

标签: java

PrintWriter fout = new PrintWriter(new BufferedWriter(
    new FileWriter("numbers.dat")
)); 
for(int i = start; i <= 100; i = i + 2) { 
    fout.print(i + ", "); 
}

现在我的输出是这样的:

2, 4, 6, 8, 10,

我想要的是什么:

2, 4, 6, 8, 10

4 个答案:

答案 0 :(得分:7)

这是一种巧妙的方式:

PrintWriter fout = new PrintWriter(new BufferedWriter(
    new FileWriter("numbers.dat")
)); 

String sep = "";
for(int i = start; i <= 100; i += 2) { 
    fout.print(sep + i);
    sep = ", ";
}

这是另一种方式:

PrintWriter fout = new PrintWriter(new BufferedWriter(
    new FileWriter("numbers.dat")
)); 

for(int i = start; i <= 100; i += 2) { 
    fout.print((i == start ? "" : ", ") + i);
}

如果不太了解PrintWriter的功能,首先使用StringBuffer生成字符串可能更有效:

PrintWriter fout = new PrintWriter(new BufferedWriter(
    new FileWriter("numbers.dat")
));

StringBuffer buffer;

for(int i = start; i <= 100; i += 2) { 
    buffer.append(i == start ? "" : ", ").append(i);
}

fout.print(buffer);

或者更有效率:

PrintWriter fout = new PrintWriter(new BufferedWriter(
    new FileWriter("numbers.dat")
));

StringBuffer buffer;

for(int i = start; i <= 100; i += 2) { 
    buffer.append(i).append(", ");
}

buffer.setLength(buffer.length()-1);

fout.print(buffer);

答案 1 :(得分:2)

打印第一个数字,然后打印“,”+数字。从i =开始+ 2开始;

答案 2 :(得分:0)

试试这个:

 PrintWriter fout = new PrintWriter(new BufferedWriter(new FileWriter("numbers.dat"))); 
 for(int i = start; i <= 100; i += 2)    { 
     if(i + 2 <= 100)  
        fout.print(i+","); 
 }

答案 3 :(得分:0)

做类似的事情 -

fout.print(i);
if (i < 100) {
    fout.print(",");
}

或写入StringBuffer并在循环

后删除尾随逗号
StringBuffer sb = new StringBuffer();
for(...){
...
}

sb.deleteCharAt(sb.length() -1);
fout.print(sb.toString());

希望这有帮助!