Home > Enterprise >  How to loop using string format and print line number?
How to loop using string format and print line number?

Time:03-11

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, "s s %-10s  .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 


CodePudding user response:

You could also try to keep a global variable called count and increase it's count everytime. Of course, change the string formatting accordingly.

int count = 1;

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

CodePudding user response:

In this case, one way is to create a method called printList using List and i each itiration.



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