【问题标题】:Perform action after certain number of loops in java在java中循环一定数量后执行操作
【发布时间】:2016-04-04 08:28:34
【问题描述】:

在数组列表中达到特定数量的循环(例如 10)后,我必须在控制台中显示一条消息,然后显示有关数组列表中剩余项目的消息。

数组列表包含从az的所有小写字母。

现在,在柜台中,我使用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 次。

【问题讨论】:

    标签: java loops iterator


    【解决方案1】:

    简单的改变是再次检查是否到达数组末尾。

    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
        }
    }
    

    【讨论】:

    • 哦,是的! :) 我认为它标志着答案!谢谢各位大师!
    【解决方案2】:

    由于您的列表中有 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
        }
    }
    

    【讨论】:

    • 问题是,10 个限制可能不同,并且其中可能会有额外的字母表 :( 有时是 5,有时是 6 :(。我想在循环中添加额外的 if etc
    • 谢谢,我会试试的:)
    【解决方案3】:

    您可以简单地添加一个附加条件,检查消息是否显示三次。如果消息未显示三次,则第三条消息将显示在数组的最后一个元素上。

    这可能适用于元素超过 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多