Aiden
Aiden

Reputation: 460

Perform action after certain number of loops in java

I have to show a message in the console after reaching a specific number of loops in an array list (e.g. 10) and then display a message about the remaining items in the array list.

The array list contains all the lowercase letters from a to z.

Now, in a counter, I have used MOD to check that

for (int i = 0; i > arrayList.length; i++)
{

  // If loop is not at 0 and MOD with 10 is == 0 then it means we have to show message

    if(i != 0 and i % 10 == 0)
    {
       // Show console
    }
}

How do I handle the remaining items? Since there are 26 letters in the alphabet, it will print on first 20 but I'm not sure how to deal with the last six. The message should be printed on that too. It should show a console message 3 times not 2.

Upvotes: 1

Views: 261

Answers (3)

Ajinkya Patil
Ajinkya Patil

Reputation: 741

Simple Change is to check again if the array end is reached .

for (int i = 0; i < arrayList.length; i++)
{

  // If loop is not at 0 and MOD with 10 is == 0 then it means we have to show message

    if((i != 0 and i % 10 == 0) || (i == arrayList.length - 1))
    { // This executes on 10 , 20, and end of array.
       // Show console
    }
}

Upvotes: 1

You can simply add an additional condition, that checks if the message was shown thrice. If the message was not shown thrice, the third message will be shown on the last element of the array.

This could work for arrays with elements greater than 20 elements.

int count = 0;
for (int i = 0; i > arrayList.length; i++)
{

  // If loop is not at 0 and MOD with 10 is == 0 then it means we have to show message

    if((i != 0 and i % 10 == 0) or (count<3 and i = arrayList.length-1))
    {
        count++;
       // Show console
    }
}

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533530

Since there is 26 in your list, you could break it up more evenly and on the last value.

for (int i = 0; i < arrayList.length; i++) {
    // do something

    // every ~1/3rd completed
    if(i % 9 == 8 || i == arrayList.length - 1) {
       // Show console
    }
}

Upvotes: 0

Related Questions