【问题标题】:How to print vertically aligned text如何打印垂直对齐的文本
【发布时间】:2011-03-11 19:11:03
【问题描述】:

我想在文件中打印以下格式的输出..

1 Introduction                                              1
 1.1 Scope                                                  1
 1.2 Relevance                                              1
   1.2.1 Advantages                                         1
     1.2.1.1 Economic                                       2
   1.2.2 Disadvantages                                      2
2 Analysis                                                  2

我无法让页码在一行中垂直对齐。这个怎么办??

【问题讨论】:

  • 文件会以固定大小的字体显示吗?
  • 始终使用默认字体大小。

标签: java string formatting alignment


【解决方案1】:

您需要左对齐第一列,右对齐第二列。

这是一个例子:

    String[] titles = {
        "1 Introduction",
        " 1.1 Scope",
        " 1.2 Relevance",
        "    1.2.1 Advantages",
        "      1.2.1.1 Economic",
        "    1.2.2 Disadvantages",
        "2 Analysis",
    };
    for (int i = 0; i < titles.length; i++) {
        System.out.println(String.format("%-30s %4d",
            titles[i],
            i * i * i // just example formula
        ));
    }

这打印(as seen on ideone.com):

1 Introduction                    0
 1.1 Scope                        1
 1.2 Relevance                    8
    1.2.1 Advantages             27
      1.2.1.1 Economic           64
    1.2.2 Disadvantages         125
2 Analysis                      216

格式%-30s %4d左对齐(@9​​87654326@标志)第一个参数宽度为30,右对齐第二个参数宽度为4。

API 链接

【讨论】:

    【解决方案2】:

    通常,使用强制最小宽度的字符串格式说明符:

    someStream.write(String.format("%60s %3d", sectionName, pageNumber));
    

    【讨论】:

    • 我试过这个。但它总是在 60 个空格后输入页码。所以行号没有垂直对齐。
    猜你喜欢
    • 2011-06-22
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多