Created
May 3, 2012 19:29
-
-
Save PerWiklander/2588493 to your computer and use it in GitHub Desktop.
String array column printer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package biz.wiklander.tools; | |
import java.util.Arrays; | |
public class StringArrayColumnPrinter { | |
public static void main(final String[] args) { | |
final String[] words = new String[] { | |
"one", | |
"duck", | |
"quacked", | |
"in", | |
"the", | |
"woods" | |
}; | |
// "one", "duck", "quacked", | |
// "in", "the", "woods", | |
formatList(words, 3, false); | |
// "duck", "in", "one", | |
// "quacked", "the", "woods", | |
formatList(words, 3, true); | |
} | |
public static void formatList( | |
final String[] words, | |
final int wordsPerLine, | |
final boolean sort) { | |
if (sort) { | |
Arrays.sort(words); | |
} | |
final int[] charCount = new int[wordsPerLine]; | |
int i = 0; | |
for (final String word : words) { | |
if (!(charCount[i % wordsPerLine] > word.length())) { | |
charCount[i % wordsPerLine] = word.length(); | |
} | |
i++; | |
} | |
i = 0; | |
for (final String word : words) { | |
if (i % wordsPerLine == 0) { | |
System.out.print("\n"); | |
} | |
System.out.print( | |
String.format( | |
"%1$-" | |
+ (charCount[i % wordsPerLine] + 4) | |
+ "s", | |
"\"" + word + "\", ") | |
); | |
i++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment