1

有没有比这样写 a 更好的解决方案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); 
            }   
4

1 回答 1

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
于 2013-09-08T14:28:59.603 回答