Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to improve nested if-else statements? [closed]

Tags:

java

algorithm

How could I improve nested if-else statements, eg in the following code example (the numbers are not neccesary the same, just example):

boolean a, b;
int result = 0;

if (a && b) {
    result = 3;
} else if (a) {
    result = 1;     
} else if (b) {
    result = 2;
}

Could this be written better somehow? Or would you think it's ok just as it is?

like image 763
membersound Avatar asked Nov 28 '22 21:11

membersound


1 Answers

For the particular numbers given:

int result = (a ? 1 : 0) + (b ? 2 : 0);

In the more general case, there's really not much wrong with the code you've already written. It's pretty concise, perfectly legible and easy to comprehend.

like image 197
Alnitak Avatar answered Dec 10 '22 08:12

Alnitak