简体   繁体   中英

How can I simplify this if-else into one statement?

How can I simplify the following code to one line (without the if-else statement)?

public static void main(String[] args) 
{
    boolean result;
    boolean a = false;
    boolean b = false;
    boolean isEmpty = false;
    if (a) {
        result = isEmpty && !b;
        System.out.println("if  " + (isEmpty && !b));
    } else {
        System.out.println("else    " + !b);
        result = !b;
    }
    System.out.println(result);
}

If a is true , you must check that isEmpty AND !b are both true . If a is false (or !a is true ), it's enough to check that !b is true .

Therefore you can replace the logic of the if statement with:

result = !b && (isEmpty || !a);

您可以使用三元运算符:

result = a ? isEmpty && !b : !b;

I think that what you are searching for is the ternary operator

In fact, you could summarize that if-else statement with something like this (but without the println):

result = (a ? isEmpty && !b : !b); System.out.println(result + "\\n");

使用以下内容:

result = a ? isEmpty && !b : !b;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM