Kirs Kringle
Kirs Kringle

Reputation: 929

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

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.

Upvotes: 6

Views: 8355

Answers (3)

matt b
matt b

Reputation: 139931

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.

Upvotes: 7

Marek Borecki
Marek Borecki

Reputation: 440

formating like this %15s makes something like text aline right. You have to write %-15s to make place for first string in 15 charts. 1st string will be align left and next string will start from 16th chart

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

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308031

The basic idea is that you describe the full format in the format string (the first argument) and provide all dynamic data as additional properties.

You mix those two by building the format string from dynamic data (the creature name, it seems), which will lead to unexpected results. Do this instead:

Creature t = temp.get(i);
System.out.printf("\t%15s [%s]\n", t.getname(), t.getCreatureType());

Upvotes: 3

Related Questions