How to format text correctly using printf() (Java)
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.
3 Answers
3
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
.
%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]
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
surely some of your past responses helped you. Why not accept some of them? It would show that you appreciate the time and effort put into trying to help you.
– Hovercraft Full Of Eels
Sep 5 '11 at 22:17