Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print vertically aligned text

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??

like image 680
razor35 Avatar asked Jul 05 '10 07:07

razor35


People also ask

How do you vertically align text?

Center the text vertically between the top and bottom margins. Select the text that you want to center. in the Page Setup group, and then click the Layout tab. In the Vertical alignment box, click Center.

How do I vertically align text and an image?

We need to create a parent element that contain both image and text. After declaring the parent element as flexbox using display: flex; we can align the items to the center using align-items: center;. Example: This example uses flexbox to vertically align text next to an image using CSS.


2 Answers

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

  • java.util.Formatter
like image 74
polygenelubricants Avatar answered Sep 19 '22 18:09

polygenelubricants


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

someStream.write(String.format("%60s %3d", sectionName, pageNumber));
like image 35
Kilian Foth Avatar answered Sep 20 '22 18:09

Kilian Foth