“缺少退货声明"在 if/for/while 内

2022-01-19 00:00:00 return java

我对 if() while()for() 语句中使用的 return 语句有疑问.

I have a question regarding return statements used within if() while() or for() statements.

正如您在下面的方法中看到的,它期望我 return 一个字符串值.问题是,如果我在 if 语句块中使用 return 语句,编译器将返回错误 missing return statement.

As you can see in the following method, it is expecting that I return a String value. The problem is that if I were to use a return statement within my if statement block, the compiler would return the error missing return statement.

public String myMethod()
{
    if(condition)
    {
        return x;
    }
}

当然,我可以将方法头更改为 void 并使用 System.out.println 而不是 return.但这是正确的方法吗?我错过了什么吗?

Of course I could change the method header to void and use System.out.println instead of return. But is this the right way to do it? Am I missing something?

推荐答案

如果在 ifwhilefor 语句,那么它可能会也可能不会返回一个值.如果它不会进入这些语句,那么该方法也应该返回一些值(可能为 null).为确保这一点,编译器将强制您在 ifwhilefor 之后编写此返回语句.

If you put a return statement in the if, while or for statement then it may or may not return a value. If it will not go inside these statements then also that method should return some value (that could be null). To ensure that, compiler will force you to write this return statement which is after if, while or for.

但是,如果您编写了一个 if/else 块并且每个块中都有一个返回,那么编译器就会知道 ifelse 将被执行并且该方法将返回一个值.所以这次编译器不会强迫你.

But if you write an if / else block and each one of them is having a return in it then the compiler knows that either the if or else will get executed and the method will return a value. So this time the compiler will not force you.

if(condition)
{
    return;
}
else
{
    return;
}

相关文章