Looking for ways to shorten my code that text aligns an array
just started learning java. This takes an array and lines the columns 开发者_Go百科up, but it seems like there would be a way shorter way of coding this. I have no ideas though..
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]);
}
Using 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]));
}
}
}
Using printf()
and 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]);
}
精彩评论