gpt4 book ai didi

java - 寻找方法来缩短我的文本对齐数组的代码

转载 作者:行者123 更新时间:2023-11-30 07:36:21 24 4
gpt4 key购买 nike

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

最佳答案

使用 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]));
}
}
}

关于java - 寻找方法来缩短我的文本对齐数组的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3648886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com