Java 中的 void 方法中的 return 关键字有什么作用? [英] What does the return keyword do in a void method in Java?

查看:50
本文介绍了Java 中的 void 方法中的 return 关键字有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看一个寻路教程,我注意到一个void 方法中的 return 语句(class PathTest,第 126 行):

I'm looking at a path finding tutorial and I noticed a return statement inside a void method (class PathTest, line 126):

if ((x < 0) || (y < 0) || (x >= map.getWidthInTiles()) || (y >= map.getHeightInTiles())) {
    return;
}

我是 Java 的新手.谁能告诉我为什么它在那里?据我所知,不允许在 void 方法中使用 return.

I'm a novice at Java. Can anyone tell me why it's there? As far as I knew, return inside a void method isn't allowed.

推荐答案

它只是在那个时候退出方法.一旦 return 被执行,其余的代码将不会被执行.

It just exits the method at that point. Once return is executed, the rest of the code won't be executed.

例如

public void test(int n) {
    if (n == 1) {
        return; 
    }
    else if (n == 2) {
        doStuff();
        return;
    }
    doOtherStuff();
}

请注意,编译器足够聪明,会告诉您某些代码无法访问:

Note that the compiler is smart enough to tell you some code cannot be reached:

if (n == 3) {
    return;
    youWillGetAnError(); //compiler error here
}

这篇关于Java 中的 void 方法中的 return 关键字有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆