views:

46

answers:

2

I want to print an output of the following format in a file..

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

I cannot get the page numbers to align vertically in a line. How to do this??

+2  A: 

Usually, with a String format specifier that enforces a minimum width:

someStream.write(String.format("%60s %3d", sectionName, pageNumber));
Kilian Foth
I had tried this. But it just types out page numbers after 60 spaces always. So the line numbers are not getting aligned vertically.
razor35
+2  A: 

You need to left-justify the first column, and right-justify the second column.

Here's an example:

    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
        ));
    }

This prints (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

The format %-30s %4d left-justifies (- flag) the first argument with width of 30, and right-justifies the second argument with width of 4.

API links

polygenelubricants