【问题标题】:How to align elements of an array into columns using string.format如何使用 string.format 将数组的元素对齐到列中
【发布时间】:2021-10-24 02:37:01
【问题描述】:

我正在尝试使用 string.format 重新创建与此类似的 straight 列:

14  Nigel       Nachtricht  Software Engineer           93  30
9   Inga        Issacs      Telemarketing Rep           54  32
20  Tenille     Tucker      Account Renewals Rep        74  32
35  Franklin    Fraser      Corporate Controller        91  32
39  Jonathan    Jacobs      VP Finance                  59  32
8   Henry       Henderson   Field Marketing Manager     81  33
13  Marjory     MacDonald   Software Engineer           94  33

这是我到目前为止的代码,但我有点卡住了,因为它只能正确获取第一个元素,并且最后的一对整数没有对齐。它效率低下而且有点随机 - string.format 对我来说仍然很新。

for(int i = 1; i < strLastName.length; i++)
        {
            
            String strIdFormat = String.format("%1$-5s", intId[i]);
            String strLastNameFormat = String.format("%1$-5s", strLastName[i]);
            String strFirstNameFormat = String.format("%1$-15s", strFirstName[i]);
            String strRoleFormat = String.format("%1$-15s", strRole[i]);
            String strAgeFormat = String.format("%1$20d", intAge[i]);
            String strGradeFormat = String.format("%1$10d", intGrade[i]);
            
            String[] nEw = {strIdFormat, strFirstNameFormat, strLastNameFormat, strRoleFormat, strAgeFormat, strGradeFormat};
            
            for(int j = 0; j < nEw.length; j++)
            {
                System.out.print(nEw[j]);
                
                if(nEw[j] == nEw[5])
                {
                    System.out.println("\n");
                }
            }
            
        }

这是我的代码打印出来的:

28   Anna           AbernathyVP Sales - EMEA                  58        74

27   Avery          AndersonJr. Account Rep                  60        73

1    Abigail        ArmstrongCEO & Chairman                   56        71

29   Brett          BurkeDirector Sales - France                  52        89

2    Benjamin       BurtonExecutive Assistant                  61        65

3    Charles        ChapmanPresident & COO                  40        71

如果有人可以提供帮助,我将不胜感激!

【问题讨论】:

    标签: java string-formatting string.format


    【解决方案1】:

    您为姓氏分配了 5 个空格。它们都比这更长,并且 String.format 解决了要求它通过超限将 20 长度的字符串推入 "%5s" 插槽的不可能性。如果你想用这种方式处理多余的部分(x.substring(0, 5)),要么编写去除多余部分的代码,要么将姓氏格式中的 5 放大很多。

    另外,您添加换行符的“如果”应该只是if (i == 5),请考虑一下。

    您单独格式化所有这些也有点奇怪。您可以只使用一种字符串格式,并且不需要1$。也许阅读文档并尝试String.format 可以做什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      • 1970-01-01
      • 2011-06-21
      相关资源
      最近更新 更多