0

在我的代码中:

if (id.isEmpty() || name.isEmpty()) {
    warlbl.setText("Warning, Empty ID or Name Fields");
    return;
}

id并且nameStringJTextFields,

是否需要return;在这里使用?

4

2 回答 2

4

是的,它可以是:

if (...) {
    ...
    return;
}

// nothing at this point will be reached if the if-statement is entered

对比

if (...) {
    ...
}

// code here will still be reached!
于 2013-08-03T23:03:55.173 回答
2

return退出您“进入”的当前方法。

当然,这不是必需的,但如果id.isEmpty()name.isEmpty(),您可能想退出该方法。所以不,是的。这不是必需的,但您可能想返回

您可以使用 return 跳出方法,继续跳过循环或 break 跳出块。

通常有两种方式:

public void test() {
    if (!statement) {
       // to something if statement is false
    } else {
       //we failed, maybe print error 
    }
}

或者:

public void test() {
    if (statement) {
       //we failed, maybe print error 
       return;
    }

    //do something if statment is false
}

但这更多是一种“风格”。大多数情况下,我更喜欢第二种方式,只是因为它的意大利面较少:P

记住。如果您的 return 语句将是执行的最后一条语句,则它是多余的。

Java参考:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

于 2013-08-03T23:03:36.897 回答