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

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

问题描述

我正在查看路径查找教程,我注意到了 void 方法中返回语句(类 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方法中返回返回

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
}

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

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