【问题标题】:return int from within if statement in a loop in java在java中的循环中从if语句中返回int
【发布时间】:2016-08-04 08:40:57
【问题描述】:

我有一个迭代等于数组长度的循环,在这个循环内我有一个方法可以进行一些处理并在里面有 if-else 结构。我希望如果某些条件为真,则重新迭代整个循环,否则继续。 提供了最低工作代码。

for(int xx=0;xx<temp.length;xx++)
    {
     rule=temp[xx][1]; 
     cons=temp[xx][2];
     fp.factprocess(fact, rule, vars, cons);
    }

fp.factprocess 的内容是这样的

if(condition==true)
  make xx = 0 in the parent loop
else
 continue

我不知道该怎么做,我使用了return语句,但它必须在最后,不能在if块中。

【问题讨论】:

标签: java arrays for-loop


【解决方案1】:

从条件测试中返回一个布尔值。如果布尔值为 true,则在循环中将 xx 设置为 -1(递增为 0)。

for(int xx=0;xx<temp.length;xx++)
    {
     rule=temp[xx][1]; 
     cons=temp[xx][2];
     boolean setXXtoZero = fp.factprocess(fact, rule, vars, cons);
     if(setXXtoZero) xx=-1;

    }

fp.factprocess:

return condition;

【讨论】:

  • 您可能希望将最后一部分重写为:'return condition;'
【解决方案2】:

是的,if块中可以有return语句。

public int getValue(int val){
  if ( value == 5 ){
    return value;
  }
  else{
    return 6;
  }
}

例如,是有效的 Java 代码。

public int getValue(int input){
  if ( input == 5 ){
    return input;
  }
}

另一方面,不是,因为如果输入不等于 5,则不会返回任何内容,但该方法必须返回一个 int,或者抛出一个异常。

这可能就是你的问题:你需要为所有可能的场景提供一个返回语句。

【讨论】:

  • 谢谢,我会试一试并更新你,它是否必须在所有可能的情况下返回?因为我不想在 else-block 中返回任何东西
  • 你必须要么返回一些东西,要么抛出异常来中断方法。最好是返回一个值
【解决方案3】:

如果你想修改循环的xx变量,我建议在你的factprocess方法中返回一个布尔值。

for (int xx = 0; xx < temp.length; xx++) {
  rule = temp[xx][1]; 
  cons = temp[xx][2];
  boolean shouldRestart = fp.factprocess(fact, rule, vars, cons);
  if (shouldRestart) {
    xx = 0;
  }
}

【讨论】:

    【解决方案4】:

    xx 传递给factprocess() 并将返回分配给xx

    for(int xx=0;xx<temp.length;xx++)
        {
         rule=temp[xx][1]; 
         cons=temp[xx][2];
         xx = fp.factprocess(fact, rule, vars, cons, xx);
        }
    

    内部factprocces()

    if (condition == true) {
        return 0
    } else {
        return xx
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-27
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 2020-08-08
      • 1970-01-01
      相关资源
      最近更新 更多