简体   繁体   中英

How can i simplify this if sequence?

I am learning java, and i got stuck in a stupid situation.

I could just throw all my code in here, but it would only confuse you even more. So I converted my logical thinking into this:

if (a) 
{
    *instruction 1*
}

if (!a && b && !c) 
{
    *instruction 2*
}

if (!a && b && c)
{
    *instruction 3*
}
else
{
    *instruction 4*
}

All I want to know is if i can simplify this, so i don't use so many "if" statements... And I'd like to know how you came to your conclusion.

Thanks in advance! (Yes, I'm dumb, help me)

EDIT:

I'm adding a truth-table with every combination of a, b and c: 真值表

You probably want to use a switch statement to make this more readable. Something like:

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be byte, short, char, and int primitive data types. Beginning with JDK7, it also works with enumerated types ( Enums in java), the String class and Wrapper classes.

As far as i can see there's a Wrapper Class for Booleans.

boolean result = switch (ternaryBool) {
case TRUE -> true;
case FALSE -> false;
case FILE_NOT_FOUND -> throw new UncheckedIOException(
    "This is ridiculous!",
    new FileNotFoundException());
// as we'll see in "Exhaustiveness", `default` is not necessary
default -> throw new IllegalArgumentException("Seriously?! 🤬");
};

https://blog.codefx.org/java/switch-expressions/

If a , b and c are local variables or otherwise guaranteed not to change while you go through the if-statements, then you can write your code as:

if (a) {
    // instruction 1
} else if (b) {
    if (!c) {
        // instruction 2
    } else {
        // instruction 3
    }
} 
if (a || !b || !c) {
    // instruction 4
}

However, it is still pretty complex. Depending on the meaning of a , b and c and how you calculate them, you should probably refactor this code into multiple methods. For example, the if-statement relating to c might fit well into a single-responsibility method.

If you want to verify whether this change is correct, you can create a truth-table with all possible combinations of a , b and c being true or false . You would check which instruction would be performed in your first code, and which instruction gets performed in the new code.

In multiple conditions, I would use the switch statement to make it easier to read.

https://beginnersbook.com/2017/08/java-switch-case/

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