嵌套'if'语句的'else'

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)

  • @Michałmutliple`return`语句比`goto`更容易阅读.如果您习惯使用RAII,它是非常安全的. (14认同)
  • @NothingsImpossible:当您在多个答案中发布您的误解时,我将在您的每条评论中进行解释.在OP的代码中,在"很好,a> 5"之后,"a> 5和b <= 7"将导致"我不喜欢你的变量" (4认同)

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)

  • 是不是写"//无限复制"更清楚?:) (2认同)
  • 这是不正确的,因为它不镜像原始示例的功能.在"a> 5"和"b <= 7"的情况下,原始的行为是打印"非常好,a> 5",然后打印"我不喜欢你的变量". (2认同)