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.
I would use this:
System.out.printf ("%-30s %1.7f %s%n", word, etc, etc2);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With