【问题标题】:Can you manipulate a For Each Loop to repeat an iteration, on Java?您可以在 Java 上操作 For Each 循环以重复迭代吗?
【发布时间】:2016-02-10 18:08:39
【问题描述】:

我必须做到以下几点:

1.- 从数据库中读取一些行(可能超过 1 行)。
2.- 用数据填充 ArrayList。
3.- 使用数据一次一行调用 WebService。
4.- 如果任何一行的传输有问题,再试3次。

问题是我使用 For Each 循环来设置数据,我不知道是否可以在该循环上重复迭代。

我正在考虑使用常规的 For 循环,如下所述: How does the Java 'for each' loop work? 但是我有两个问题:
在我的情况下,我怎样才能得到正确的方法来获得“长度”?
在我的情况下,我必须在哪里使用方括号 [i]?

我应该重新排列代码吗?

这是我的代码简介:

ArrayList<SomeBean> v = new ArrayList<SomeBean>();

while(index < 1000) 
{   
    //Read some data from DB

    //Fill the arraylist

    for(SomeBean s : v)
    {
        if (repeat == 0)
        {
            //Use the Data of the current iteration to invoke Webservice
            String column1 = s.getColumn1();
            String column2 = s.getColumn2();
            String column3 = s.getColumn3();
            ...
        }
        else
        {
            //Don´t use the Data of current iteration, try again with the same data
        }

        try 
        {
            //Invoke WebService and send the data

            if (answer == OK)
            {
                //Print OK
            }
            else
            {
                //Print NOT OK
            }
        }                       
        catch (Exception) 
        {
            //Print the Exception
            repeat++;

           if (repeat > 3)
           {
            repeat = 0; //Go to read a new group of data
            index++;
           }                   
        }
    }
}

【问题讨论】:

  • 你必须在 for-each 循环中有另一个循环才能重复。更好的方法是有一个单独的方法来调用 web 服务,并在出错时重试n 次。从父 for-each 循环调用该方法一次。这样,如果您想更改重试机制等,您可以在单独的方法中执行此操作。
  • 感谢@Nivas,我在try and catch 中放置了另一个循环。不优雅但解决了问题。

标签: java arraylist foreach iteration


【解决方案1】:

这是一个完美的递归任务。这里的想法是,如果逻辑中发生错误并且尝试次数超过预定限制,则失败。否则,它会通过递归调用自身再次尝试。

// Our class variables
private int attempts = 0, limit = 3;

// A method to call our recursive method for the first time.
void BeginProcessing()
{
     ProcessData();
}

// Our recursive method containing our read logic.
void ProcessData()
{
    try
    {
        /* Insert read logic here. */
    }
    catch(Exception)
    {
        attempts++;

        if (attempts<=limit)
        {
            ProcessData();
        }
        else
        {
            System.out.println("Attempted to process " + limit + " times.");        
        }
    }
}

【讨论】:

  • 非常好的方法,但我必须对我的代码做太多的重新排列。谢谢。
  • 如果您不关心效率,评论您的问题的人可以工作 - 添加另一个循环。但是,如果您有额外的时间,我强烈建议您尝试实现这个递归解决方案,因为它的大 O 是 O(n),比您当前的 O(n^3) 三重嵌套循环解决方案效率高出三倍。虽然我完全尊重您不将其标记为“正确”答案的决定,因为您目前不会使用它,但对于未来尝试使用 Google 类似解决方案的开发人员来说,将其标记为这样可能是明智之举。最好的问候,奥姆努斯鲁修斯
  • 没问题!祝你好运。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多