简体   繁体   English

return关键字在Java中的void方法中做了什么?

[英]What does the return keyword do in a void method in Java?

I'm looking at a path finding tutorial and I noticed a return statement inside a void method (class PathTest , line 126): 我正在寻找一个路径查找教程 ,我注意到一个void方法中的return语句(类PathTest ,第126行):

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

I'm a novice at Java. 我是Java的新手。 Can anyone tell me why it's there? 谁能告诉我它为什么存在? As far as I knew, return inside a void method isn't allowed. 据我所知,不允许在void方法内return

It just exits the method at that point. 它只是在那时退出方法。 Once return is executed, the rest of the code won't be executed. 执行return ,其余代码将不会执行。

eg. 例如。

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
}

You can have return in a void method, you just can't return any value (as in return 5; ), that's why they call it a void method. 你可以在void方法中return ,你只是不能返回任何值 (如return 5; ),这就是为什么他们称之为void方法。 Some people always explicitly end void methods with a return statement, but it's not mandatory. 有些人总是使用return语句明确地结束void方法,但它不是强制性的。 It can be used to leave a function early, though: 可以用来尽早保留一个功能:

void someFunct(int arg)
{
    if (arg == 0)
    {
        //Leave because this is a bad value
        return;
    }
    //Otherwise, do something
}

关键字只是从调用堆栈中弹出一个帧,将控件返回到函数调用之后的行。

Java语言规范说如果方法返回void,则可以返回没有表达式。

它的功能与带有指定参数的函数返回相同,但它不返回任何内容,因为没有任何内容可以返回,并且控制权被传递回调用方法。

It exits the function and returns nothing. 它退出函数并且不返回任何内容。

Something like return 1; return 1; would be incorrect since it returns integer 1. 会返回错误,因为它返回整数1。

See this example, you want to add to the list conditionally. 请参阅此示例,您要有条件地添加到列表中。 Without the word "return", all ifs will be executed and add to the ArrayList! 如果没有单词“return”,将执行所有ifs并添加到ArrayList!

    Arraylist<String> list =  new ArrayList<>();

    public void addingToTheList() {

    if(isSunday()) {
        list.add("Pray today")
        return;
    }

    if(isMonday()) {
        list.add("Work today"
        return;
    }

    if(isTuesday()) {
        list.add("Tr today")
        return;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM