0

我对java编程相当陌生,我想知道是否有某种方法可以用某种“超级”返回语句结束其父方法。

前任:

public class test {

    public method1 () {
        ...some code...

        if (someValue == someValue2) {return;}

        ...more code...
    }

    public static void main(String[] args) {
        ...some code...

        method1();

        ...more code...
    }
}

我希望 method1 的 return 语句也结束父方法的执行(在本例中为 main 方法)而不添加 if 语句,基于返回的值,在 method1 的调用之后。那可能吗?

谢谢!

4

2 回答 2

1

不。

但是在您的示例中,退出将起作用(即停止执行所有操作),但是如果您想要“更多控制”,则让您的方法返回一个值并检查它。保持一致。例如,我喜欢使用 0=success,其他都是某种错误代码。

public class test {

    public int method1 () {
        ...some code...
        if (someValue == someValue2) {return -1;}
        ...more code...
        return 0;
    }

    public static void main(String[] args) {
        ...some code...

        if (method1() == 0) {
            ...more code...
        }
    }
}
于 2013-10-17T22:33:19.677 回答
0

方法返回到调用它时的代码。所以,基本上你是在返回给调用者。你可以放一个布尔返回来实现你的实现:

public method1 () {
        ...some code...

        if (someValue == someValue2) {return false;}
        else return true;

    }

    public static void main(String[] args) {
        ...some code...

        result = method1();
        if(!result)
        return;

        ...more code...
    }

或者,如果您希望程序退出,您可以使用System.exit()

于 2013-10-17T22:37:04.620 回答