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.
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());
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With