简体   繁体   English

返回true然后从for循环中断

[英]Return true and then break from a for loop

I'm new to java. 我是java的新手。 I have been trying to do something without success. 我一直试图做一些没有成功的事情。 Basically What I want to do is to create a method that return true or false. 基本上我想要做的是创建一个返回true或false的方法。 The method gets some parameter, checks if a certain array is full, if not it pushes the parameters to the to the first cell that isn't empty, return true and NOT keep checking for the rest of the array. 该方法获取一些参数,检查某个数组是否已满,如果不是,则将参数推送到非空的第一个单元格,返回true并且不继续检查数组的其余部分。 If the array is full it just return false. 如果数组已满,则返回false。 This is the code: 这是代码:

public boolean add( param1, param2, param3 ){
 for( int i = 0; i < array.length; i++ ){
   if ( array[i] == null ){
     array[i] =  new SomeObject( param1, param2, param3 ); 
     return true;
     break;
     }
  }
  return false;
}

But I get error- "unreachable statement" for "break;". 但我得到错误 - “无法恢复声明”为“休息”。 Any help? 有帮助吗?

Thanks in advance! 提前致谢!

Since you have a return statement, you don't need to break from the loop, since the return statement ends the execution of the method. 由于你有一个return语句,所以你不需要从循环break ,因为return语句结束了方法的执行。 Just remove the break statement. 只需删除break语句即可。

As some people insist on a function having a single point of return, the function can be reformulated as follows, matching the apparent expectation of the original question. 由于一些人坚持具有单一回报点的功能,因此可以如下重新表述该功能,匹配原始问题的明显期望。

public boolean add( param1, param2, param3 ){
    boolean result = false;
    for( int i = 0; i < array.length; i++ ){
        if ( array[i] == null ){
            array[i] =  new SomeObject( param1, param2, param3 ); 
            result = true;
            break;
        }
    }
    return result;
}

Yes, Because the moment the control encounters a return statement it just gets out of a method, switch or a loop etc. so any code written below the return statement will be just "unreachable." 是的,因为当控件遇到一个return语句时,它就会退出一个方法,转换或循环等,所以在return语句下面写的任何代码都只是“无法访问”。 So its always advisable to place the return at the last of the block (of a method) unless required and it is also advisable not to write any code after the return statement in a single block lest you should get an error. 因此,除非需要,否则始终建议将返回放在块的最后一个块(方法)中,并且建议不要在单个块中的return语句之后写入任何代码,以免出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM