【问题标题】:Moving to a previous statement inside for loop移动到 for 循环中的上一条语句
【发布时间】:2017-09-19 00:05:40
【问题描述】:

我有一个类似于下面给出的 for 循环。

for(int i=0; i<10; i++)
{
   boolean condition = checkCondition();    /* line 3 */

   if(condition)
   {
     if(some other condition A)
     {
       move to line 3;
     }
     else if(some other condition B)
     {
      call_method_B();
     }
     else
     {
      call_method_C();
     }
  }
  else
  {
    call_method_D();
  }
}

如何使程序返回到上述 if 语句中的第 3 行?我不想破坏迭代。需要在同一个迭代中,只需要回到第 3 行。

【问题讨论】:

  • 你需要一个循环。
  • 我相信,如果你有一些基本条件,你可以更喜欢递归方法,而不是使用迭代方法
  • 是的,我知道我需要一种递归方法。我不能像 shmosel 建议的那样使用循环,因为我需要的功能是递归的。但我无法弄清楚该怎么做。你有什么想法吗?
  • @zim :我已经使用递归方法发布了答案。您可以参考该方法。
  • 你可以使用 break / goto 标签吗?

标签: java for-loop if-statement


【解决方案1】:

要在同一迭代中,只需在调用 continue 之前将 i 减 1。 请注意,如果条件从未改变,这将使您进入无限循环。

for(int i=0; i<10; i++)
{
   boolean condition = checkCondition();    /* line 3 */

   if(condition)
   {
     if(some other condition A)
     {
       move to line 3;
       i--;  //this will cancel out the i++ in the for loop  
       continue; //this will bring you back to line 3
     }

     ... the rest of your codes

【讨论】:

  • 我认为这是正确的解决方案....您也可以将int i = 0移出,使用while (i &lt; 10),然后将i++放在需要递增的位置
  • 我相信这是我提到的简单代码的最佳方法,谢谢:)所以+1为您的回答。但是对于我的问题,递归方法非常有用。
【解决方案2】:

我不想中断迭代。需要在同一个迭代中,只需要回到第 3 行。

我认为你需要一个 while 循环。然后,您可以更好地控制迭代时间。当你得到conditionA检查时,i不会改变,循环重复,否则你可以说i++

int i = 0;
while (i < 10) {
    if (checkCondition()) {
        if (some other condition A) {
            // continue the iteration
        } else if (some other condition B) {
            call_method_B();
            i++;
        } else {
            call_method_C();
            i++;
        }
    } else {
        call_method_D();
        i++;
    }
}

【讨论】:

  • 感谢您的意见。 +1为您的答案。递归方法对我的特定问题很有帮助,但你的方法也解决了我遇到的问题。 :)
【解决方案3】:

我相信您的问题似乎需要递归方法而不是迭代方法。

上述问题可以通过以下方式使用递归方法解决:

public void checkRecursive()
{
    boolean condition = checkCondition(); 

    if (base_condition_to_avoid_recursion)
        return;

    if (condition)
    {
        if (some other condition A)
        {
            checkRecursive();
        }
        else if (some other condition B)
        {
            call_method_B();
        }
        else
        {
            call_method_C();
        }
    }
    else
    {
        call_method_D();
    }
}

【讨论】:

  • 感谢您指导我采用递归方法。这对我的问题最有效。我接受这个答案,因为它是我实际代码的最佳方法,它更复杂,并且有一个单独的递归方法也有助于代码的其他部分。
猜你喜欢
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-30
  • 2022-11-26
  • 2015-09-28
  • 1970-01-01
相关资源
最近更新 更多