将一维数组格式化为表格时遇到问题

时间:2021-05-11 17:29:08

标签: java arraylist format

afterEach(async function() {
const png = await browser.takeScreenshot();
allure.createAttachment("Screenshot", Buffer.from(png, "base64"), "image/png");
});

我不确定这是否是对该数组进行表化的正确方法,但它大多有效。问题是元素之间存在奇怪的不均匀空间,我不知道为什么。我尝试过添加制表符/空格,但没有任何效果。

Weird spaces between elements

2 个答案:

答案 0 :(得分:0)

我会选择String#format() / System.out.printf()

System.out.printf("%21s %9s %9s %9s\n", 
  df.format(/* ... */), 
  df.format(/* ... */), 
  df.format(/* ... */), 
  df.format(/* ... */));

%9s 表示:长度为 9 个字符的字符串。如果字符串少于 9 个字符,则在前面附加空格,因此文本右对齐。如果您希望文本左对齐,可以使用 %-9s

System.out.printf("%11s | %9s | %9s | %9s\n", "Orig. Temp.", "Temp in C", "Temp in F", "Temp in K");
System.out.printf("%11s | %9s | %9s | %9s\n", "213.0", "99.6", "213.0", "372.7");
System.out.printf("%11s | %9s | %9s | %9s\n", "321.0", "321.0", "609.8", "594.1");

产生:

Orig. Temp. | Temp in C | Temp in F | Temp in K
      213.0 |      99.6 |     213.0 |     372.7
      321.0 |     321.0 |     609.8 |     594.1

(或左对齐:%-9s

Orig. Temp. | Temp in C | Temp in F | Temp in K
213.0       | 99.6      | 213.0     | 372.7    
321.0       | 321.0     | 609.8     | 594.1 

(或居中)

private static void print() {
// header
  System.out.printf("%11s | %9s | %9s | %9s\n", "Orig. Temp.", "Temp in C", "Temp in F", "Temp in K");
  // values
  System.out.printf("%-11s | %-9s | %-9s | %-9s\n", center("213.0", 11), center("99.6", 9), center( "213.0", 9), center("372.7", 9));
  System.out.printf("%-11s | %-9s | %-9s | %-9s\n", center("321.0", 11), center("321.0", 9), center("609.8", 9), center("594.1", 9));
}

private static String center(String str, int size) {
  if (str.length() >= size) {
    return str;
  }

  final StringBuilder builder = new StringBuilder();
  for (int i = 0; i < (size - str.length()) / 2; i++) {
    builder.append(' ');
  }
  builder.append(str);
  for(int i = 0; i < (builder.length() - size); i++) {
    builder.append(' ');
  }
  return builder.toString();
}

产生:

Orig. Temp. | Temp in C | Temp in F | Temp in K
   213.0    |   99.6    |   213.0   |   372.7  
   321.0    |   321.0   |   609.8   |   594.1  

答案 1 :(得分:0)

您可以使用字符串填充使每一列的字符数相同。

String padToRight(String input, String pad, int length) {
    while(input.length() < length) {
        input += pad;
    }
    return input;
}

padToRight("hello", " ", 7) 将返回 "hello "

相关问题