java:如何获取for循环中的内部细节

时间:2011-11-11 15:12:23

标签: java for-loop

public void two(final BeanForm[] captureddata)
{
  for (BeanForm form : captureddata) 
  {
    if (form.getCyclicType() != null) 
    {
      logger.info("The Cyclic Type is"+ form.getCyclicType().value());
    }

    if (form.getTicketType() != null) 
    {
      logger.info("The Ticket Type is"+ form.getTicketType().value());
    }
  }
}

上面的代码工作正常,但我在日志文件中看到的输出是(如果BeanForm的长度为2)

11/Nov/2011 20:15:51   - The Cyclic Type is  DTI
11/Nov/2011 20:15:51   - The Ticket Type is MMTS
11/Nov/2011 20:15:51   - The Cyclic Type is DTI
11/Nov/2011 20:15:51   - The Ticket Type is MMTS

我只是想知道是否有可能获得数组细节,比如这个数据属于哪个数组 例如

The array[1]  Cyclic Type is  DTI 
The array[2]  Cyclic Type is  SAG

5 个答案:

答案 0 :(得分:2)

如果你的意思是索引进入循环 - 没有。你需要明确地这样做:

for (int i = 0; i < capturedData.length; i++)
{
    BeanForm form = capturedData[i];
    // Now you have both form and i.
}

答案 1 :(得分:2)

只需使用外部计数:

public void two(final BeanForm[] captureddata)
{
  int count = 0;

  for (BeanForm form : captureddata) 
  {
    if (form.getCyclicType() != null) 
    {
      logger.info(count + " The Cyclic Type is"+ form.getCyclicType().value());
    }

    if (form.getTicketType() != null) 
    {
      logger.info(count + " The Ticket Type is"+ form.getTicketType().value());
    }

    count++;
  }
}

或作为循环的正常

public void two(final BeanForm[] captureddata)
{
  for (int i=0; i<captureddata.length; i++)
  {
    BeanForm form = capturedata[i];

    if (form.getCyclicType() != null) 
    {
      logger.info(i+ " The Cyclic Type is"+ form.getCyclicType().value());
    }

    if (form.getTicketType() != null) 
    {
      logger.info(i+ " The Ticket Type is"+ form.getTicketType().value());
    }
  }
}

答案 2 :(得分:0)

一种可能的方法是在for循环中维护一个计数器,你可以使用计数器和数组[],如:

int i=0;
for-each loop
{
    //print array[i]
    //increment i
}

答案 3 :(得分:0)

public void two(final BeanForm[] captureddata)
{
    for (i = 0; i < captureddata.length(); i++) {
        BeanForm form = captureddata[i]
        if (form.getCyclicType() != null) 
        {
            logger.info("The array["+i+"] Cyclic Type is"+ form.getCyclicType().value());
        }

        if (form.getTicketType() != null) 
        {
            logger.info("The array["+i+"] Ticket Type is"+ form.getTicketType().value());
        }
    }
}

答案 4 :(得分:0)

同意马修的解决方案 ,只需使用另一个计数数字,并在循环结束时增加。

但是,在日志文件中,请注意您是否希望以“array [0]”或“array [1]”开头