如何使用字符串格式循环并打印行号?

How to loop using string format and print line number?

我想使用简单循环为每次迭代添加行号。

我希望显示适合用户观看。


    @Override
    public String toString() {

       return  String.format(Locale.US, "%15s %12s %-10s  %10.2f ",
                 this.firstName, this.lastName,this.age, this.length);
}


我想要的输出

Nr      Name              Age         Length[M]

 1     Mona Beckham        23           1.80 
 2     John Robinhood      23           1.80 

我得到的输出

       Mona Beckham        23           1.80 
       John Robinhood      23           1.80 


在这种情况下,一种方法是使用 List 创建一个名为 printList 的方法 和 i++ 每次迭代。



            ListIterator iterator = list.listIterator();
            int i = 1;
            while (iterator.hasNext()){
                System.out.println(i + "\t" + iterator.next());
            i++;
            }
        ```

您也可以尝试保留一个名为 count 的全局变量并每次都增加它的计数。当然,相应地更改字符串格式。

int count = 1;

@Override
public String toString() {
    return String.format(Locale.US, "%15s %12s %-10s  %10.2f ",
       count++, this.firstName, this.lastName,this.age, this.length);
}

执行此操作的方法几乎是无限的。下面是一个演示 Person class,其中包含一个名为 toTableString() 的方法,该方法接受两个特定参数。第一个参数是 Person 的列表接口 (List<Person>),它将包含要以 table 类型格式打印到控制台的 Person 实例。第二个参数是布尔值并且是可选的。它确定该方法是否还应为返回的 table 类型格式化字符串提供带下划线的 Header 行。默认情况下这是 false,因此如果没有为此参数提供任何内容或提供 false,则不提供 Header 行。但是,如果提供了布尔值 true,则提供带下划线的 Header 行。

这只是一个例子。有很多方法可以解决这个问题:

示范人物class:

public class Person {
    
    private String firstName;
    private String lastName;
    private int age;
    private double length;

    public Person() {    }    
    
    public Person (String firstName, String lastName, int age, double length) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.length = length;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getLength() {
        return length;
    }

    public void setLength(double length) {
        this.length = length;
    }

    @Override
    public String toString() {
        return firstName + ", " + lastName + ", " + age + ", " + length;
    }
    
    /**
     * Returns a string which lists the supplied instances of Person in a table 
     * type format.<br><br>
     * 
     * @param personsList (List Interface of Person) A list of Person instances 
     * to convert to table type format.<br>
     * 
     * @param applyHeader (Optional - boolean) Default is boolean false whereas 
     * no header and header underline is supplied within the returned String. If 
     * boolean true is supplied then a Header line describing the column names 
     * and an underline is also included within the returned table type formated 
     * String.<br>
     * 
     * @return (String) A String with instances of Person data formated in a 
     * table type format.
     */
    public String toTableString(java.util.List<Person> personsList, boolean... applyHeader) {
        String ls = System.lineSeparator();
        boolean addHeader = false;
        if(applyHeader.length > 0) {
            addHeader = applyHeader[0];
        }
        
        StringBuilder sb = new StringBuilder("");
        if (addHeader) {
            String header = String.format(java.util.Locale.US, "%-8s %-20s %-6s %10s",
                                          "No.", "Name", "Age", "Length[m]") + ls;
            String underline = String.join("", java.util.Collections.nCopies(header.length()-2, "=")) + ls;
            sb.append(header).append(underline);
        }
        
        for (int i = 0; i < personsList.size(); i++) {
            String name = personsList.get(i).firstName + " " + personsList.get(i).lastName;
            sb.append(String.format(java.util.Locale.US, "%-8d %-20s %-6d %7.2f %n",
                     (i + 1), name, personsList.get(i).age, personsList.get(i).length));
        }
        return sb.toString();
    }
    
}

如何使用 toTableString() 方法:

Person persons = new Person();
List<Person> list = new ArrayList<>();
list.add(new Person("Mona", "Beckham", 23, 1.80));
list.add(new Person("John", "Robinhood", 23, 1.91));
list.add(new Person("Fred", "Flintstone", 36, 1.72));
   
System.out.println("Without Header Line...");
System.out.println();
System.out.println(persons.toTableString(list));
   
System.out.println();
    
System.out.println("With Header Line...");
System.out.println();
System.out.println(new Person().toTableString(list, true));

并且控制台 Window 应该显示:

Without Header Line...

1        Mona Beckham         23        1.80 
2        John Robinhood       23        1.91 
3        Fred Flintstone      36        1.72 


With Header Line...

No.      Name                 Age     Length[m]
===============================================
1        Mona Beckham         23        1.80 
2        John Robinhood       23        1.91 
3        Fred Flintstone      36        1.72