[英]How Can I get a While loop with an If statement in Java to stop after a certain number of loops?
[英]Perform action after certain number of loops in java
在達到數組列表中的特定循環數(例如 10)后,我必須在控制台中顯示一條消息,然后顯示有關數組列表中剩余項目的消息。
數組列表包含從a
到z
所有小寫字母。
現在,在櫃台中,我使用MOD
來檢查
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
}
}
剩余物品如何處理? 由於字母表中有 26 個字母,因此它會打印前 20 個字母,但我不確定如何處理后六個字母。 消息也應該印在上面。 它應該顯示控制台消息 3 次而不是 2 次。
簡單的更改是再次檢查是否到達數組末尾。
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
}
}
由於您的列表中有 26 個,您可以更均勻地將其分解為最后一個值。
for (int i = 0; i < arrayList.length; i++) {
// do something
// every ~1/3rd completed
if(i % 9 == 8 || i == arrayList.length - 1) {
// Show console
}
}
您可以簡單地添加一個額外的條件,檢查消息是否顯示三次。 如果消息未顯示三次,則第三條消息將顯示在數組的最后一個元素上。
這適用於元素大於 20 個元素的數組。
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.