If和elseif之间的java差异?
我想知道为什么要使用else if
语句,而不是多个if
语句?例如,这样做的区别是什么:
if(i == 0) ...
else if(i == 1) ...
else if(i == 2) ...
这是:
if(i == 0) ...
if(i == 1) ...
if(i == 2) ...
他们似乎做了完全相同的事情
你可以在下面搜索框中键入要查询的问题!
我想知道为什么要使用else if
语句,而不是多个if
语句?例如,这样做的区别是什么:
if(i == 0) ...
else if(i == 1) ...
else if(i == 2) ...
这是:
if(i == 0) ...
if(i == 1) ...
if(i == 2) ...
他们似乎做了完全相同的事情
# 1 楼答案
如果您使用了多个
if
语句,那么如果条件是true
,那么所有语句都将被执行。如果您使用了if
和else if
组合,只有一个会在第一个值为真的地方执行# 2 楼答案
if
语句检查所有多个可用的if
。 当else if
语句失败时,if
语句返回true,但它不会检查else if
因此,这取决于您的需求如何
# 3 楼答案
第一个示例不一定会运行3个测试,第二个示例不会给出任何返回或goto
# 4 楼答案
区别在于,如果第一个
if
为真,那么所有其他else if
都不会执行,即使它们的计算结果为真。然而,如果它们是单个的if
,那么如果它们的计算结果为true,那么所有的if
都将被执行# 5 楼答案
# 6 楼答案
对于第一种情况:一旦else if(或if)成功,剩余的else if将不进行测试。然而,在第二种情况下,即使所有(或其中一个)都成功,每个if都将进行测试