刚开始学习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]);
}
最佳答案
使用字符串格式:
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]));
}
}
}
关于java - 寻找方法来缩短文本对齐数组的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3648886/