简体   繁体   English

如何优化编写多行输出?

[英]How can I optimize writing multiple lines of output?

Is there a better solution than writing a System.out.println in this way? 是否有比以这种方式编写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); 
            }   

Create a StringBuilder, append your Strings to the StringBuilder, and then print it in one System.out.println call. 创建一个StringBuilder,将您的字符串附加到StringBuilder,然后在一个System.out.println调用中将其打印。

Oh, and you can easily nest two for loops and make your code much more readable. 哦,您可以轻松地嵌套两个for循环,并使代码更具可读性。

eg, 例如,

  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();
  • Note: code not compiled nor tested. 注意:代码未经编译或测试。
  • Note 2: code as written risks trying to extract items beyond the size of the ds list. 注意2:尝试提取超出ds列表大小的项目具有书面风险。 You will want to set maxSomething based on the size of your ds list 您将需要根据ds列表的大小设置maxSomething

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM