Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java printf formatting to print items in a table or columns

I am wanting to print things in a neat columns using printf.

happening       0.083333    [4]
hi              0.083333    [0]
if              0.083333    [8]
important       0.083333    [7]
is              0.250000    [3, 5, 10]
it              0.166667    [6, 9]
tagged          0.083333    [11]
there           0.083333    [1]
what            0.083333    [2]

I have this code System.out.printf("%s %.6f %s \n", word, web.getFrequency(word), loc);, but it prints out this:

happening  0.083333  [ 4 ] 
hi  0.083333  [ 0 ] 
if  0.083333  [ 8 ] 
important  0.083333  [ 7 ] 
is  0.250000  [ 3 5 10 ] 
it  0.166667  [ 6 9 ] 
tagged  0.083333  [ 11 ] 
there  0.083333  [ 1 ] 
what  0.083333  [ 2 ] 

Any help would be appreciated.

like image 322
Vayelin Avatar asked Dec 25 '22 12:12

Vayelin


2 Answers

I would use this:

System.out.printf ("%-30s %1.7f %s%n", word, etc, etc2);
like image 158
dmolony Avatar answered Dec 28 '22 06:12

dmolony


You can get the max length of all the word strings, and store that length in a variable, max. Use a for loop to get that max, and then create a String that has the format with concatenating the normal printf format with the max variable to be used as the width. Additionally \t puts in a tab character.

int max = 0;
for (int ii = 0; ii < numberOfStrings; ii++)
{
   max = (word.length() > max) ? word.length() : max;
}
String format = "%" + max + "s\t%.6f\t%s \n";
System.out.printf(format, word, web.getFrequency(word), loc);
like image 30
lakerka Avatar answered Dec 28 '22 08:12

lakerka