你可以做這樣的事情
// Get the maximum length of any string in the array, or 0.
private static int getMaxLength(String[] in) {
int c = 0;
if (in != null && in.length > 0) {
for (String i : in) {
i = (i != null) ? i.trim() : "";
if (i.length() > c) {
c = i.length();
}
}
}
return c;
}
// Pad any input string to the minimum length.
private static String padString(String in, int min) {
in = (in != null) ? in.trim() : "";
StringBuilder sb = new StringBuilder(in);
while (sb.length() < min) {
sb.append(' ');
}
return sb.toString();
}
private static void makeFile(String[] name,
String[] nickname, String[] capital,
String[] flowers, String[] population) {
PrintWriter out = null;
try {
out = new PrintWriter("out.txt");
// Add 1 to get at least 1 space between the maximum and the next item.
int nameLen = getMaxLength(name) + 1;
int nickLen = getMaxLength(nickname) + 1;
int capitalLen = getMaxLength(capital) + 1;
int flowersLen = getMaxLength(flowers) + 1;
int populationLen = getMaxLength(population);
for (int i = 0; i < name.length; i++) {
out.println(padString(name[i], nameLen)
+ padString((nickname.length > i) ? nickname[i]
: "", nickLen)
+ padString((capital.length > i) ? capital[i] : "",
capitalLen)
+ padString((flowers.length > i) ? flowers[i] : "",
flowersLen)
+ padString((population.length > i) ? population[i]
: "", populationLen));
}
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace(System.err);
} finally {
out.close();
}
}
public static void main(String[] args) {
String[] name = { "Alabama", "Alaska", "Arizona" };
String[] nickname = { "Yellowhammer State",
"Last Frontier", "Grand Canyon State" };
String[] capital = {
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "Y", "Z" };
String[] flowers = { "Rose", "Carnation", "Orchid" };
String[] population = { "1", "100", "1000" };
makeFile(name, nickname, capital, flowers,
population);
}