加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:30:37 所属栏目:Java 来源:网络整理
导读:我已经按照以下方式编写了一个方法: if (something) { return 1;}the rest of the code 在我看来,该方法返回1,然后执行其余的代码.真的可以吗不返回停止代码的执行.它不是,我如何强制一种方法停止? 添加 这是代码(根据要求): for (int i=availableTime; i
我已经按照以下方式编写了一个方法:
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.");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读