愚蠢的问题,使用两个单独的if子句是一个好习惯,或者如果使用if else子句则使用一个,例如:
if (a = 1)
(dosomething)
if (a=2)
(do other thing)
OR
if (a=1)
(do something)
else if (a=2)
(do other thing)
这两个如果条件不同的话。变量a用作比较器,根本不变。
这两种方式按预期工作,没有任何编程错误,我只是问一下什么是好的做法并推荐?
答案 0 :(得分:3)
取决于你想要达到的目标。
在第一种情况下,两个条件将被评估为独立 - 即使两个条件都是 true 。
在第二种情况下,如果第一个条件被评估为 true ,则将跳过 else-if 分支。
您可以在JLS上看到完整的解释。
答案 1 :(得分:2)
如果您使用第一种方式,则会检查每个if语句。在第二种方式中,如果一个是正确的,则忽略以下所有其他情况。
因此,如果存在复杂的if条件,则可能需要更长的时间。
通过检查这些值(a == 1,a == 2,a == 3,...),尝试切换!
答案 2 :(得分:2)
这两项测试明显不同。在第一种情况下,如果首先a
为1而do something
将a
的值更改为2,则还会执行do other thing
。在第二个变体中不是这种情况。那么使用哪一个取决于你想要实现的目标。
答案 3 :(得分:1)
这取决于你的意思。如果您希望仅在第一个条件不为真的情况下测试第二个条件,请使用if (...) else if (...)
选项。相反,如果您希望单独检查两个条件,请使用if (...) if (...)
。
人们不能谈论两件意味着不同事物的事物之间的最佳实践。只要在每种情况下写下您设计的算法会告诉您编写的内容,即在代码中忠实地表达您的设计。
答案 4 :(得分:1)
如果条件是互斥的(只有一个可以在同一时间),第二种方式。另外,如果两种情况都可以同时发生,那么第一种方式就是正确的。
答案 5 :(得分:1)
我会使用更容易阅读的风格。
清晰度总是比难以遵循的代码更好。
执行速度不会成为一个大问题。
答案 6 :(得分:0)
至少在Java字节码中,有三种不同的场景:
if(a == 3) // load an int from local variable a, load int value 3 onto the stack
// if they are not equal go (branch) to line a = 4;
a = 5; // load int value 5 onto the stack, save it into the variable
else // there's no instruction for this line as it's behavior was
// described in line if(a == 3)
a = 4; // load int value 4 onto the stack, save it into the variable
if(a == 3) // load an int from local variable a, load int value 3 onto the
// stack, if they are not equal go (branch) to line if(a != 3)
a = 5; // load int value 5 onto the stack, save it into the variable
// go to line after a = 4;
else if(a != 3) // load an int from local variable a, load int value 3 onto the
// stack, if they are equal go (branch) to line after a = 4;
a = 4; // load int value 4 onto the stack, save it into the variable
if(a == 3) // load an int from local variable a, load int value 3 onto the stack
// if they are not equal go (branch) to line if(a != 3)
a = 5; // load int value 5 onto the stack, save it into the variable
if(a != 3) // load an int from local variable a, load int value 3 onto the stack
// if they are equal go (branch) to line after a = 4;
a = 4; // load int value 4 onto the stack, save it into the variable
int a = 5;
int ifelse()
{
if(a == 5) a = 3; // true, go to return
else a = 6;
return a; // returns 3
}
int ifelseif()
{
if(a == 2) a = 3; // false, go to next line
else if(a == 3) a = 6; // false, go to next line
else if(a == 5) a = 9; // true go to return
return a; // returns 9 (btw you might use switch for this)
}
int ifif()
{
if(a == 5) a = 3; // true, go to next line
if(a == 3) a = 6; // true, go to return
return a; // returns 6
}