BigClassic BigClassic - 3 months ago 8
Java Question

Aligning columns

I need to make the output of the following strings displayed in columns:

System.out.printf("Weight of Item 1: %10d%n", ITEM_1);
System.out.printf("Weight of Item 2: %10d%n", ITEM_2);
System.out.printf("Weight of Item 3: %10d%n", ITEM_3);
System.out.printf("Total Weight Kilograms: %10d%n", totalWeightKilograms);


I can get the variables that are input into the string to shift to where I want. I can't get the text format before the variables. Basically, the output I get:

Weight of Item 1: 38
Weight of Item 2: 23
Weight of Item 3: 12
Total Weight Pounds: 73


What I want is:

Weight of Item 1: 38
Weight of Item 2: 23
Weight of Item 3: 12
Total Weight Pounds: 73


I need the indentation(width) of the string as much I need it to be.

Answer

You could put your item(s) and String(s) into array(s), and specify a format length with %s as long as your longest String (22 characters). Something like,

String[] msg = { "Weight of Item 1", "Weight of Item 2", "Weight of Item 3",
        "Total Weight Kilograms" };
int[] items = { ITEM_1, ITEM_2, ITEM_3, totalWeightKilograms };
for (int i = 0; i < msg.length; i++) {
    System.out.printf("%22s: %10d%n", msg[i], items[i]);
}

Which outputs (as requested)

      Weight of Item 1:         38
      Weight of Item 2:         23
      Weight of Item 3:         12
Total Weight Kilograms:         73