JulieF
JulieF

Reputation: 27

In Java can I select a place to begin a line/column when printing?

For example, say I want to write to a text file, and I want to line up my results into columns like so:

Peanut Butter       Crunchy
Jelly               Purple
Bread               Wheat
Milk                Whole

\t obviously doesn't line up the second column when the first words are different lengths. Is lining them up possible?

Upvotes: 0

Views: 54

Answers (1)

jluckin
jluckin

Reputation: 662

Yes, it is possible. You want to pad the strings to the right with white spaces. For example, if you specify that each column starts every 20 characters and your string is 12 characters, you need to add 8 whitespace characters to the end.

You could hand code a loop or you could use string.format(). I took a look around online and found this easy method which you can use. http://www.rgagnon.com/javadetails/java-0448.html

public static String padRight(String s, int n) {
    return String.format("%1$-" + n + "s", s);
}

s is the string that you want to pad, n is the ideal length.

For example,

padRight("test", 10") -> "test      "

To add to your code, just format each line. For example, for your first line, you could do

String line = padRight(peanutButterString, 20) + peanutButterAttribute

Make sure your values are in an array and you can easily loop through it and create the properly formatted string.

Upvotes: 2

Related Questions