Reputation: 2461
I am trying to print a two column output of words and word count. I seem to be having an issue with the formatting. Here is my line of code for the printf
:
public void inOrderTraverseTree(Node focusNode){
if(focusNode != null){
inOrderTraverseTree(focusNode.lChild);
//focusNode.visit();
System.out.printf("%-15s %15d", focusNode.key, focusNode.count);
inOrderTraverseTree(focusNode.rChild);
}
}
After looking at my output again, it seems that my issue is that the second column follows the length of the word in the first column. Is there a way to set a width for an output so that the count does not depend on the end of the word?
Upvotes: 0
Views: 439
Reputation: 51
You may also be missing a trailing "%n" (carriage return) and having the first element of the second line run into the second element of the first (assuming this is being called in a loop).
System.out.printf("%-20s %-15d%n", string1, string2);
Otherwise, like another answer points out, the second element should be an integer, not a String (at least based on your formatting).
Here's an example:
String[] text = new String[] { "apple", "the" };
int[] data = new int[] { 123, 4567 };
for (int i = 0; i < text.length; i++) {
System.out.printf("%-20s %-15d%n", text[i], data[i]);
}
The output is:
apple 123 the 4567
Obviously if the word you want to stick into the first column is wider than 20 chars it will push the second column over by that many chars.
Upvotes: 1
Reputation: 2953
Actually the pattern "%-20s %-15d" is fine, as long as you provide a number as second argument. I wonder how you got this output because providing a String to a "%-15d" generates a runtime error.
Upvotes: 0
Reputation: 39437
Try this.
System.out.printf("%20s%15d", "123451234512345", 10000);
Also in your code this string2 needs to be int actually, not string.
Upvotes: 2