本文介绍了Java Return不退出方法(循环)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个学校的项目工作,该方法的方法中有许多嵌套循环.我可以验证我的代码是否达到返回真值";在返回假"之前的陈述;使用太多System.out.println语句.

I'm working on a project for school where I have many nested loops in a method. I can verify that my code is reaching the "return true;" statement before a "return false;" using way too many System.out.println statements.

在任何情况下return不会立即退出该方法.在我的代码中,它达到了return true;",但随后继续执行该方法.

Is there any case where return does not immediately exit the method. In my code it reaches the "return true;", but then continues working through the method.

谢谢-第一次发帖,但长期学习其他问题的学生

Thanks - first post, but long time student from other questions

显示我的代码-这是针对UC Berkeley项目的,因此他们不允许我们发布完整的代码.这是重要的部分.

Show my code - This is for a UC Berkeley project so they aren't allowing us to post our full code. Here is the important parts.

我的代码中没有"try语句".这是我的方法的结尾,它具有大量的循环(而& for)循环.

There are no "try statements" in my code. This is the very end of my method which has a ton of loops (while & for) loops.

if (x == 7 && turn == 5){
                    System.out.println("TRUE RESULT");
                    return true;


                }

                nextVictory(turn, x, y, color,z);
                alive = false;
            }

        }


          }
    }
    System.out.println("FALSE RESULT");
    return false;
}

我有打印声明以确认我在哪里.结果如下:

I have print statement to verify where I'm at. Here are the results:

真实结果

错误结果

错误结果

错误结果

错误结果

推荐答案

唯一想到的情况是 return 语句是否在 try - finally 块内. finally 块仍将执行.

The only case that comes to mind is if the return statement were inside a try-finally block. The finally block would still get executed.

另一种可能表现出类似行为的情况是,如果您的方法是递归的.在这种情况下,嵌套调用中的 return 语句实际上会返回给调用者.但是,如果调用者是方法本身,则该方法的外观可能会继续通过 return 返回执行.

Another case that could exhibit similar behaviour is if your method is recursive. In that case, a return statement in a nested call would actually return to the caller. However, if the caller is the method itself, this could have the appearance of the method continuing to execute past the return.

这篇关于Java Return不退出方法(循环)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:52