One 'else' for nested 'if' statements

c#, c++, if-statement, java

Solution

Boolean logic 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");
    }
}

Alternatively - if you want loads of checks -

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");
    }
}

Problem

I've got a problem which can be simplified to this: ``` 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"); } ``` I would like to use only one `else` instead of two since they are the same code. What I thought of was creating an additional method, which will return combined `true``false`, but this is a serious overkill. Another option would be a `goto`, but this would make code less readable and unsafe. What is the way to do it, avoiding checking the same condition many times and making it as readable as possible?

Original source

Related problems