Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding counter in enhanced for loop

I have a code which takes name and number from user and save those in an arraylist as object.

I am using this enhanced for loop to printout all name and number which is stored in that arraylist ...

for(Objectclass p : Test) {
    System.out.println("Name: " + p.getName() + "   Number: " + p.getNumber());
    }

it prints like Name: blah blah Number: blah blah

now i want to add counter number before Name and number like 1.Name: blah blah Number: blah blah 2.Name ... number 3.Name ... number

... how can i add that ? if i use another for loop inside this for loop to add counter number ... it prints again and again.

like image 632
jtfkyo Avatar asked Sep 16 '26 08:09

jtfkyo


2 Answers

Make a counter variable declared outside of the enhanced for-loop.

int i = 0;
for(Objectclass p : Test) {
    System.out.println(++i + ". Name: " + p.getName() + "   Number: " + p.getNumber());
}

Or so, you don't have a useless variable after it, switch back to the old method.

for(int i = 0; i < Test.size();){
    Objectclass p = Test.get(i++);
    System.out.println(i + ". Name: " + p.getName() + "   Number: " + p.getNumber());
 }
like image 131
Patrick J Abare II Avatar answered Sep 18 '26 21:09

Patrick J Abare II


This should work:

int i = 0;
for(Objectclass p : Test) 
{
    i++;
    System.out.println(i + ". Name: " + p.getName() + "   Number: " + p.getNumber());
}

Sadly, there is no way of extracting an iteration index from an enhanced for-loop.

like image 36
Nekojimi Avatar answered Sep 18 '26 20:09

Nekojimi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!