2013-11-25 74 views
-1

所以我能夠對齊前2列,但我怎麼得到其他3列對齊以及?在第2部分格式化列

這是我的代碼:

private static void makeFile(String[] name, String[] nickname, String[] capital, String[] flowers, String[] population) throws FileNotFoundException { 
PrintWriter out = new PrintWriter ("out.txt"); 
for (int i = 0; i< 50 ; i++){ 
    out.printf("%-15s %s \n", name[i], nickname[i]+ " " + capital[i] + " " +flowers[i]+ " "+ population[i]); 

} 
out.close(); 
} 

}

這是我得到: http://i1059.photobucket.com/albums/t424/dondon4720/statealignmentpart_zps38235d60.png

回答

0

你需要把你的所有列中的printf 像

out.printf("%-15s %-15s %-15s %-15s %-15s\n", name[i], nickname[i], capital[i], flowers[i], population[i]); 

您可能需要t o根據文字的長度調整-15。

0

你可以做這樣的事情

// 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); 
}