lundi 25 décembre 2017

Execute Code Between If and Else-if Statement in Java

I got this code:

if (conditionX) {

                    doX();
                }



else if (conditionY) {
                    boolean isSomethingTrue = findOutIfSomethingIsTrue();
                    if (anotherConditionIsTrue) {
                        doY();
                    }
                }


boolean conditionXYZ = checkIfXYZIsTrue();

else if (conditionXYZ != true) {  // <- eclipse wants me to delete this 'else' statement

                    doXYZ();

                }

When I run this code eclipse complains that "Syntax error on token "else", delete this token". I understand this is because I have the code:

boolean conditionXYZ = checkIfXYZIsTrue();

between both else if statements. But I cannot check the value of conditionXYZ unless I set the value of conditionXYZ in between both else if statements.

The only other similar question I found on SO is this one and it suggests to use two if statements. The problem is I don't want conditionXYZ to be evaluated if conditionY is true.

My other option is to use two if statements and add a return statement for each if statement. But I do not find this solution to be elegant in terms of code design.

My third option is to checkIfXYZIsTrue() before executing any of the if statements but this is not efficient because if conditionY is true we don't need to check conditionXYZ.

Any ideas?

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire