【发布时间】: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