如何优化写入多行输出?

时间:2013-09-08 14:28:08

标签: java

有没有比以这种方式编写System.out.println更好的解决方案?

String nl = System.getProperty("line.separator");

for (k=0; k<=ds.size()-counter-1; k=k+counter){
            System.out.println (metric+" "+ds.get(k)+" "+ds.get(k+2)+" sensor=A cell="+ cellName + nl +
            metric+" "+ds.get(k)+" "+ds.get(k+3)+" sensor=B cell="+ cellName + nl + 
            metric+" "+ds.get(k)+" "+ds.get(k+4)+" sensor=C cell="+ cellName + nl + 
            metric+" "+ds.get(k)+" "+ds.get(k+5)+" sensor=D cell="+ cellName + nl +
            metric+" "+ds.get(k)+" "+ds.get(k+6)+" sensor=E cell="+ cellName + nl + 
            metric+" "+ds.get(k)+" "+ds.get(k+7)+" sensor=F cell="+ cellName + nl + 
            metric+" "+ds.get(k)+" "+ds.get(k+8)+" sensor=G cell="+ cellName + nl + 
            metric+" "+ds.get(k)+" "+ds.get(k+9)+" sensor=H cell="+ cellName + nl +
            metric+" "+ds.get(k)+" "+ds.get(k+10)+" sensor=I cell="+ cellName + nl +    
            metric+" "+ds.get(k)+" "+ds.get(k+11)+" sensor=L cell="+ cellName + nl +    
            metric+" "+ds.get(k)+" "+ds.get(k+12)+" sensor=M cell="+ cellName + nl +
            metric+" "+ds.get(k)+" "+ds.get(k+13)+" sensor=N cell="+ cellName); 
            }   

1 个答案:

答案 0 :(得分:5)

创建一个StringBuilder,将你的字符串附加到StringBuilder,然后在一个System.out.println调用中打印它。

哦,你可以轻松地嵌套两个for循环,让你的代码更具可读性。

如,

  StringBuilder stringBuilder = new StringBuilder();
  Formatter formatter = new Formatter(stringBuilder);
  int maxSomething = 12;
  String template = metric + " %s %s sensor=%c cell=" + cellName + nl;
  for (int i = 0; i < ds.size()-counter-1; i = i + counter) {
     for (int j = 0; j < maxSomething; j++) {
        formatter.format(template, ds.get(i), ds.get(i + j + 2), (char)('A' + j));
     }
  }
  // the toString() below isn't necessary but is present for clarity
  System.out.println(stringBuilder.toString());
  formatter.close();
  • 注意:代码未编译也未经过测试。
  • 注2:代码为写入风险,试图提取超出ds列表大小的项目。您需要根据ds列表的大小设置maxSomething