Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print columns in java txt file

I am trying to print multiple arrays on one .txt file having one array print then have another column crated and have another array print how do i format this to work??

I cant remember the formatting commands to do this I need all the columns to align right now i have this

private static void makeFile(String[] name, String[] nickname, String[] capital, 
           String[] flowers, String[] population) throws FileNotFoundException 
{
    PrintWriter out = new PrintWriter ("out.txt");

    for (int i = 0; i< 50 ; i++)
         out.println( name[i] +" \t "+  nickname[i] );

    out.close();
}

This is what prints

enter image description here

How do i fix it so they are all aligned and there are 3 more columns to add to this how do i get them to align as well ??

like image 937
dondon4720 Avatar asked Dec 04 '22 08:12

dondon4720


2 Answers

You should use String.format like

String.format("%-30s %s", name[i], nickname[i])

where 30 is maximum length of name.

like image 84
Nikolay Avatar answered Dec 21 '22 10:12

Nikolay


You can use printf instead of println, with C-style format strings.

out.printf("%-16s%-24s\n", name[i], nickname[i]);

This will print the name[i] left-aligned in a 16-character placeholder, then print nickname[i] in a 24-character wide column. When adding more columns, you can specify the maximum required number of characters in the format string. The - sign is added for aligning the strings to left.

like image 41
Sufian Latif Avatar answered Dec 21 '22 11:12

Sufian Latif