Search code examples
javastringooptostringstringbuilder

How to loop using string format and print line number?


I want to add a line number to each iteration using a simple loop.

I want the display to be suitable for the user to see.


    @Override
    public String toString() {

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


The output I want

Nr      Name              Age         Length[M]

 1     Mona Beckham        23           1.80 
 2     John Robinhood      23           1.80 

The output I get

       Mona Beckham        23           1.80 
       John Robinhood      23           1.80 



Solution

  • The number of ways you can do this is almost limitless. Below is a demo Person class which contains a method named toTableString() which accepts two specific arguments. The first argument is a List Interface of Person (List<Person>) which would contain the instances of Person you want to print to console in table type format. The second argument is boolean and is optional. It determines whether or not the method should also supply an underlined Header Line to the returned table type formatted string. By default this is false so if nothing is supplied for this argument or false is supplied then no Header line is provided. If however boolean true is supplied then a underlined Header line is supplied.

    This is just a single example. There re so many ways you could go with this:

    Demo Person 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();
        }
        
    }
    

    How you might use the toTableString() method:

    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));
    

    And the Console Window should display:

    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