2010-09-06 41 views
2

剛開始學習java。這需要一個數組,並將列排成一行,但似乎有一種更短的編碼方式。我沒有任何想法,但..尋找方法來縮短我的代碼,使文本與陣列對齊

int longestString = 0; 
    int numberOfChars; 

    String information[][] = { {"First Name:", "a" }, 
     {"Last Name:", "b"}, 
     {"Nickname:", "c"}, 
     {"Example:", "d"}, 
     {"Example:", "e"}, 
     {"Example:", "f"}, 
     {"Example:", "g"}}; 

    for(int i=0; i<information.length; i++){ 
    if (information[i][0].length() > longestString) { 
    longestString = information[i][0].length(); 
    } 
    } 

    numberOfChars = longestString + 1; 

    for(int i=0; i<information.length; i++){ 
    while (information[i][0].length() < numberOfChars){ 
    information[i][0] += " "; 
    } 
    } 

    for (int i=0; i<information.length; i++){ 
    System.out.print(information[i][0]); 
    System.out.println(information[i][1]); 
    } 

回答

3

使用的String.format:

package so3648886; 

public class Align { 
    /** 
    * @param args 
    */ 
    public static void main(final String[] args) { 
     int longestString = 0; 
     final String information[][] = { { "First Name:", "a" }, 
       { "Last Name:", "b" }, { "Nickname:", "c" }, 
       { "Example:", "d" }, { "Example:", "e" }, { "Example:", "f" }, 
       { "Example:", "g" } }; 

     for (int i = 0; i < information.length; i++) { 
      if (information[i][0].length() > longestString) { 
       longestString = information[i][0].length(); 
      } 
     } 

     for (int i = 0; i < information.length; i++) { 
      System.out.println(String.format("%-" + longestString + "s %s", 
        information[i][0], information[i][1])); 
     } 
    } 
} 
1

使用printf()Collections.max()

final String information[][] = { { "First Name:", "a" }, 
     { "Last Name:", "b" }, { "Nickname:", "c" }, 
     { "Example:", "d" }, { "Example:", "e" }, { "Example:", "f" }, 
     { "Example:", "g" } }; 

final List<String[]> infoList = Arrays.asList(information); 
final int maxLength = Collections.max(infoList, new Comparator<String[]>(){ 
    @Override public int compare(String[] info1, String[] info2) { 
     return info1[0].length() - info2[0].length(); 
    } 
})[0].length(); 

final String formatter = "%-" + maxLength + "s %s\n"; 
for (int i = 0; i < information.length; i++) { 
    System.out.printf(formatter, information[i][0], information[i][1]); 
}