Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format text correctly using printf() (Java)

Tags:

java

printf

Hello I want to print something so they are aligned.

    for (int i = 0; i < temp.size(); i++) {
        //creatureT += "[" + temp.get(i).getCreatureType() + "]";
        creatureS = "\t" + temp.get(i).getName();
        creatureT = " [" + temp.get(i).getCreatureType() + "]";
        System.out.printf(creatureS + "%15a",creatureT + "\n");
   }

and the output is

    Lily      [Animal]
    Mary         [NPC]
    Peter      [Animal]
    Squash          [PC]

I just want the [Animal], [NPC], and [PC] to be aligned like

    Lily      [Animal]
    Mary      [NPC]
    Peter     [Animal]
    Squash    [PC]

Say I know that no name will be greater then 15 characters.

like image 874
Kirs Kringle Avatar asked Apr 27 '11 15:04

Kirs Kringle


People also ask

What is %s and %D in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"

What does %d do Java?

%d: Specifies Decimal integer. %c: Specifies character. %T or %t: Specifies Time and date. %n: Inserts newline character.


1 Answers

I think you'll find it's a lot easier to do all of the formatting in the format string itself, i.e.

System.out.printf("\t%s [%s]\n", creature.getName(), creature.getCreatureType());

which would print

  Lily [Animal]
  etc...

You can consult the String formatting documentation on the exact format to use to print a minimum of 15 spaces for a string to achieve the alignment effect, something like

System.out.printf("\t%15s[%s]\n", creature.getName(), creature.getCreatureType());

The key is specifying a "width" of 15 chars for the first item in the argument list in %15s.

like image 70
matt b Avatar answered Nov 14 '22 23:11

matt b