返回If语句内部和外部 [英] A Return inside and outside an If Statement

查看:109
本文介绍了返回If语句内部和外部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个相当容易回答的问题,但它一直困扰着我。

This is probably a fairly easy question to answer, but it has been bugging me some time.

如果在if语句中有一个return语句,那么方法(在Java语言中),但是我在最后添加另一个作为一个全能的并且为了避免错误,如果if语句为真,两个返回值是否会被一个接一个地触发?

If there is a return statement inside an if statement, inside a method (in the Java language), but I add another at the end as a catch-all and to avoid the error, are both return values going to be fired one after the other if the if statement is true?

一个例子:

public int getNumber() {
 if( 5 > number) {
 return 5;
 }
 return 0;
 }

结果:方法返回5,然后通过堆栈逻辑,此后不久返回0 。

Result: Method returns 5, and then via stacks logic, returns 0 shortly thereafter.

或者,我是否需要像这样使用外部变量:

Or, do I need to use an outside variable like so:

int num = 1;
public int getNumber() {
 if( 5 > number) {
 num = 5;
 }
 return num;
 }

结果:方法将变量num更改为5,然后返回num以供使用。我想在这种情况下,根据变量的用法,不一定需要return语句。

Result: Method changes variable num to 5, then num is returned for use. I suppose in this case, the return statement wouldn't necessarily be required depending on the variable's usage.

提前致谢。

推荐答案

不,两个值都不会被返回。 return 语句停止在那里执行方法,并返回其值。实际上,如果在返回后面有代码,编译器知道由于 return 而无法访问,它会抱怨。

No, both values aren't going to be returned. A return statement stops the execution of the method right there, and returns its value. In fact, if there is code after a return that the compiler knows it won't reach because of the return, it will complain.

你不需要在之外使用一个变量,如果在最后返回它。但是,如果您的方法冗长而复杂,这种技术有助于提高可读性和清晰度,因为只使用了一个 return 语句。

You don't need to use a variable outside the if to return it at the end. However, if your method is long and complex, this technique can help readability and clarity because only one return statement is used.

这篇关于返回If语句内部和外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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