【问题标题】:How to format String on the left and int on the right?如何格式化左边的String和右边的int?
【发布时间】:2018-03-21 13:21:42
【问题描述】:

我正在尝试从 2 个数组中获取格式化输出,其中一个是国家,另一个是人口,应该提供如下输出:

埃及 | 92592000 法国 | 66991000 日本 | 126860000 瑞士 | 8401120

我收到的唯一提示是我应该计算每列所需的最大宽度,然后使用它来对齐值。 这是我迄今为止想出的,但在格式化时坚持要输出任何东西。

public static void main (String[] args) throws java.lang.Exception
{
    String [] countries = {"Egypt", "France", "Japan", "Switzerland"};
    int[] populations = {92592000, 66991000, 126860000, 8401120};
    printTable(countries, populations);
}

public static void printTable(String[] countries, int[] populations){
    int longestInput = 0;
    for(int i = 0; i < countries.length; i++){
        int countLength = countries[i].length();
        int popLength = String.valueOf(populations[i]).length();
        if(countLength + popLength > longestInput)
            longestInput = countLength + popLength;
    }

    for(int i = 0; i < countries.length; i++)
    System.out.format("%-10",countries[i] + " | " + populations[i]);
}

【问题讨论】:

  • 您需要计算两个最大长度:国家和人口。然后你用最长的国家填充每个国家,用最长的流行填充每个人口,加入这些字符串并打印它们。
  • 为什么你的 main 抛出 java.lang.Exception?
  • 它是因为我尝试在底部格式化,如果我删除其他所有工作,或者可能来自导入 java.util.*;导入java.lang.*;导入java.io.*;我忘记放入sn-p
  • 这是否意味着有例外?我认为您必须在格式中添加“转换”。看this answer。
  • 看起来它可以帮助我现在尝试一下,我只有在尝试格式化输出时才会出现异常,因为如果我不正常工作

标签: java format formatter


【解决方案1】:

这是一个小例子:

public static void main (String[] args) throws java.lang.Exception
  {
    String [] countries = {"Egypt", "France", "Japan", "Switzerland"};
    int[] populations = {92592000, 66991000, 126860000, 8401120};
    printTable(countries, populations);
  }

  public static void printTable(String[] countries, int[] populations){
    int countryLength = 0;
    long populationLength = 0;

    for(String country: countries){ //get longest country
      if (country.length() > countryLength)
        countryLength = country.length();
    }
    for(int i : populations) { //get longest number
      if(String.valueOf(i).length() > populationLength)
        populationLength = String.valueOf(i).length();
    }

    for(int i = 0; i < countries.length; i++) // print it out
      System.out.format("%-"+ (countryLength+1) +"s|%" + (populationLength+1) +"d\n",countries[i], populations[i]);
  }

首先获得最长的国家:

for(String country: countries){ //get longest country
  if (country.length() > countryLength)
    countryLength = country.length();
}

其次用String.valueOf(i).length()得到最长的人口:

for(int i : populations) { //get longest number
  if(String.valueOf(i).length() > populationLength)
    populationLength = String.valueOf(i).length();
}

最后用System.out.format打印出来:

System.out.format("%-"+ (countryLength+1) +"s|%" + (populationLength+1) +"d\n",countries[i], populations[i]);

【讨论】:

    【解决方案2】:

    使用 Java 8

    public static void main (String[] args) throws java.lang.Exception {
        String [] countries = {"Egypt", "France", "Japan", "Switzerland"};
        int[] populations = {92592000, 66991000, 126860000, 8401120};
        printTable(countries, populations);
    }
    
    public static void printTable(String[] countries, int[] populations) {
        if (countries.length == 0 || populations.length == 0 || countries.length != populations.length) {
            return;
        }
        int longestCountry = Arrays.stream(countries)
                .map(String::toString)
                .mapToInt(String::length)
                .max()
                .getAsInt();
        int longestPop = Arrays.stream(populations)
                .mapToObj(Integer::toString)
                .mapToInt(String::length)
                .max()
                .getAsInt();
    
        for (int i = 0; i < countries.length; i++) {
            System.out.printf("%-" + longestCountry + "s | %" + longestPop + "d%n", 
                countries[i], 
                populations[i]);
        }
    }
    

    诀窍是使用流来获取长度并使用负格式字符串填充字符串的右侧。

    【讨论】:

    • 如果countries 或population 为空数组,您的方法可能会引发异常
    • 添加了检查,我假设两者都不会为空以简化代码
    【解决方案3】:

    您可能正在寻找的模式是:

    "%-" + maxCountryLength + "s | %" + maxPopulationLength + "d\n"
    
    • %-Xs 表示“X 字符宽度,左对齐 String”
    • %Xd 表示“X 字符宽度,右对齐数字”
    • \n 表示占一行

    该方法可能如下所示:

    public static void printTable(String[] countries, int[] populations) {
        int defaultLength = 10;
        int maxCountryLength = stream(countries).mapToInt(String::length).max().orElse(defaultLength);
        int maxPopulationLength = stream(populations).mapToObj(Integer::toString).mapToInt(String::length).max().orElse(defaultLength);
    
        for (int i = 0; i < countries.length; i++) {
            System.out.format("%-" + maxCountryLength + "s | %" + maxPopulationLength + "d\n", countries[i], populations[i]);
        }
    }
    

    结果:

    Egypt       |  92592000
    France      |  66991000
    Japan       | 126860000
    Switzerland |   8401120
    

    【讨论】:

      【解决方案4】:

      我重写了 printTable 方法,效果很好:

      public static void printTable(String[] countries, int[] populations)
      {
          if(countries.length != 0)
          {
      
              int longestNameInput = countries[0].length();
              int longestPopInput = String.valueOf(populations[0]).length();
      
              for(int i = 0; i < countries.length; i++)
              {
                  int countLength = countries[i].length();
                  int popLength = String.valueOf(populations[i]).length();
      
                  if(countLength > longestNameInput)
                      longestNameInput = countLength;
      
                  if(popLength > longestPopInput)
                      longestPopInput = popLength;
              }
      
              for(int i = 0; i < countries.length; i++)
              {
                  System.out.print(countries[i]);
                  for(int j = 0; j < (longestNameInput - countries[i].length()); j++)
                      System.out.print(" ");
                  System.out.print(" | ");
      
                  for(int k = 0; k < (longestPopInput - String.valueOf(populations[i]).length()); k++)
                      System.out.print(" ");
                  System.out.println(populations[i]);
              }
      
          }
      }
      

      【讨论】:

        【解决方案5】:
        public static void main (String[] args) throws java.lang.Exception {
            String [] countries = {"Egypt", "France", "Japan", "Switzerland"};
            Integer[] populations = {92592000, 66991000, 126860000, 8401120};
            printTable(countries, populations);
        }
        
        public static void printTable(String[] countries, Integer[] populations){
            int longestInput = 0;
            for(int i = 0; i < countries.length; i++){
                int countLength = countries[i].length();
                int popLength = String.valueOf(populations[i]).length();
                if(countLength + popLength > longestInput)
                    longestInput = countLength + popLength;
            }
        
            String longestString = getLongestString( countries );
            System.out.format("longest string: '%s'\n", longestString);
        
            Integer longestNumber = getLongestNumber( populations );
            System.out.format("longest Number: '%s'\n", longestNumber);
        
            for(int i = 0; i < countries.length; i++)
                System.out.format("%-" + longestString.length() + "s | %" + String.valueOf(longestNumber).length() + "d\n", countries[i], populations[i]);
        
        }
        

        在字符串数组中查找最长的字符串

        public static String getLongestString(String[] array) {
            int maxLength = 0;
            String longestString = null;
            for (String s : array) {
                if (s.length() > maxLength) {
                    maxLength = s.length();
                    longestString = s;
                }
            }
            return longestString;
        }
        

        在整数数组中查找最长的数字

        public static Integer getLongestNumber(Integer[] array) {
            int maxLength = 0;
            Integer longestNumber = null;
            for (Integer i : array) {
                if (String.valueOf(i).length() > maxLength) {
                    maxLength = String.valueOf(i).length();
                    longestNumber = i;
                }
            }
            return longestNumber;
        }
        

        输出«

        longest string: 'Switzerland'
        longest Number: '126860000'
        Egypt       |  92592000
        France      |  66991000
        Japan       | 126860000
        Switzerland |   8401120
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-01-13
          • 2016-09-23
          • 1970-01-01
          • 2014-07-09
          • 1970-01-01
          • 1970-01-01
          • 2018-12-27
          相关资源
          最近更新 更多