vendredi 15 janvier 2021

How to use if condition more efficiently?

I have a little knowledge in programming but I have a doubt about the following if statement.

val age = 21
if(age >= 21) {
    println("You can drink now")
} else if(age >= 18) {
    println("You can vote now")
} else if(age >= 16) {
   println("You can drive now")
} else{
   println("You are too young")
}

In the above if statement, all conditions are true but I know only the first condition will be executed. If I want to check all the conditions are true, I could use seperate if conditions for all criteria. Is there any way to make this possible in a more efficient way. Please share your knowledge. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire