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

标签 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]);
  }  

最佳答案

使用字符串格式:

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/

相关文章:

java - Jetty 9.2.3 中是否存在 JDBC ConnectionPool 泄漏?

java - BigQueryIO.Read 查询与作业 : Query

Java打开浏览器进程导致30秒延迟

java - 案例研究 : Is this an effective way to split a file?

java - 是什么导致了 neo4j 的这种糟糕表现?

java - Hibernate:org.hibernate.PersistentObjectException:传递给持久化的分离实体

java - 为什么我不能在方法之外调用变量?

java - 使用 Gson 读取数据时避免从整数进行双重转换

java - ProcessBuilder 和 FileHandler 之间的区别

java - PanelImagen[,0,0,0x0,无效,layout=java.awt.BorderLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]