“缺少返回语句"在 if/for/while 内 [英] "Missing return statement" within if / for / while

查看:32
本文介绍了“缺少返回语句"在 if/for/while 内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

正如你在下面的方法中看到的,它期望我返回一个字符串值.问题是,如果我在 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 中放入 return 语句> 语句然后它可能会或可能不会返回一个值.如果它不会进入这些语句,那么该方法也应该返回一些值(可能为空).为确保这一点,编译器将强制您在 ifwhilefor 之后编写此 return 语句.

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;
}

这篇关于“缺少返回语句"在 if/for/while 内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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