寻找缩短文本对齐数组的代码的方法

时间:2010-09-06 03:42:07

标签: java

刚开始学习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]);
  }  

2 个答案:

答案 0 :(得分: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 :(得分: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]); 
}