微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/java/122363.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐