java – “return”是否停止执行方法?

前端之家收集整理的这篇文章主要介绍了java – “return”是否停止执行方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经按照以下方式编写了一个方法
if (something) {
   return 1;
}
the rest of the code

在我看来,该方法返回1,然后执行其余的代码.真的可以吗不返回停止代码的执行.它不是,我如何强制一种方法停止?

添加

这是代码(根据要求):

for (int i=availableTime; i>0; i=i-1) {
            final int sec = i;
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    String lbl = "<html>";
                    lbl += "</html>";
                    timeLeftLabel.setText(lbl);
            }
            });
            try {Thread.sleep(1000);} catch (InterruptedException e) {}
            parameterFromClientsListener = clientsListener.getValue(userName,parameterToGet);
            if (!parameterFromClientsListener.equals("null")) {
                output = parameterFromClientsListener;
                game.log.fine(userName + " set (by button) " + parameterToGet + " to be equal to " + output + " . [IMPORTANT]");
                return output;
            }
    }

    game.log.fine("The partner selection phase is expired.");
    // This code is executed if the Submit button was not pressed and the time run out.
    if (parameterToGet.equals("partner")) {
        tellMyChoice(parameterToGet,this.partnerFromForm,"timer of" + field);
        output = this.partnerFromForm;
    }
    game.log.fine(parameterToGet + " was submitted by timer (not by OK button).");
    } else {
    output = parameterFromClientsListener;
    }
    game.log.fine(userName + " set (by timer)" + parameterToGet + " to be equal to " + output + " . [IMPORTANT]");
    return output;
}

我运行这段代码两次.在每种情况下,我都会生成一个日志文件.在两个日志文件中,我看到“set(by button)”语句(在返回之前是直接的).但问题是在第二个日志文件中我看到“timer of”语句.如果达到“设定(按钮)”,则不能达到.怎么会这样?我需要提到的是,“set(by button)”和“timer”不会发生在我的代码中的任何地方(它们只发生一次).

添加3

代码可以看出,我没有finally语句.

解决方法

这不是真的,return语句将停止任何以下代码. (唯一的例外是返回语句在try {}块中,后来有一个finally {}块.
if(0==0){
       return;
    }
    System.out.println("This will not print.");
原文链接:https://www.f2er.com/java/122363.html

猜你在找的Java相关文章