Mic*_*hał 16 c# c++ java if-statement
我有一个问题可以简化到这个:
parameters: a, b
if (a > 5)
{
Print("Very well, a > 5");
if (b > 7)
Print("Even better, b > 7");
else
{
Print("I don't like your variables");
}
}
else
{
Print("I don't like your variables");
}
Run Code Online (Sandbox Code Playgroud)
我想只使用一个else而不是两个,因为它们是相同的代码.我想到的是创建一个额外的方法,它将返回组合的true`false`,但这是一个严重的矫枉过正.
另一种选择是a goto,但这会使代码更不易读和不安全.
有什么方法可以做到这一点,避免多次检查相同的条件并使其尽可能可读?
Chr*_*rew 21
void doILikeYourVariables(int a, int b) {
if (a > 5) {
Print("Very well, a > 5");
if (b > 7) {
Print("Even better, b > 7");
return;
}
}
Print("I don't like your variables");
}
Run Code Online (Sandbox Code Playgroud)
Old*_*eon 13
布尔逻辑101:
public void test(int a, int b, int c) {
boolean good = true;
if (good = good && a > 5) {
System.out.println("Very well, a > 5");
}
if (good = good && b > 7) {
System.out.println("Even better, b > 7");
}
if (good = good && c > 13) {
System.out.println("Even better, c > 13");
}
// Have as many conditions as you need, and then
if (!good) {
System.out.println("I don't like your variables");
}
}
Run Code Online (Sandbox Code Playgroud)
或者 - 如果你想要大量的支票 -
enum Tests {
A_gt_5 {
@Override
boolean test(int a, int b, int c) {
return a > 5;
}
},
B_gt_7 {
@Override
boolean test(int a, int b, int c) {
return b > 7;
}
},
C_gt_13 {
@Override
boolean test(int a, int b, int c) {
return c > 13;
}
};
abstract boolean test (int a, int b, int c);
}
public void test(int a, int b, int c) {
boolean good = true;
for ( Tests t : Tests.values() ) {
good = good && t.test(a, b, c);
if (!good) {
break;
}
}
if (!good) {
System.out.println("I don't like your variables");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4911 次 |
| 最近记录: |