如何打印垂直对齐的文本

raz*_*r35 5 java string formatting alignment

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

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
Run Code Online (Sandbox Code Playgroud)

我不能让页码在一行中垂直对齐.这该怎么做??

pol*_*nts 10

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

这是一个例子:

    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
        ));
    }
Run Code Online (Sandbox Code Playgroud)

打印(如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
Run Code Online (Sandbox Code Playgroud)

格式%-30s %4d左对齐(-标记)第一个参数,宽度为30,右对齐第二个参数,宽度为4.

API链接


Kil*_*oth 6

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

someStream.write(String.format("%60s %3d", sectionName, pageNumber));
Run Code Online (Sandbox Code Playgroud)