简体   繁体   中英

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.

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

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 .

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM