Search code examples
javamaxbluej

Convert from single way selection to multi way selection


I need convert from single way selection to multi way selection, but i know using switch statements i cant have something like a>=b, so how do i do it?

if(num1 >= num2 && num1 >= num3 && num1 >= num4)
   largestnum=num1;

if(num2 >= num1 && num2 >= num3 && num2 >= num4)
   largestnum=num2;

if(num3 >= num1 && num3 >= num2 && num3 >= num4)
   largestnum=num3;

if(num4 >= num1 && num4 >= num3 && num4 >= num2)
   largestnum=num4;

Solution

  • This is the multiway if-else statement:

    if(num1 >= num2 && num1 >= num3 && num1 >= num4) {
        largestnum = num1;
    } else if(num2 >= num3 && num2 >= num4) {
        largestnum = num2;
    } else if(num3 >= num4) {
        largestnum = num3;
    } else {
        largestnum = num4;
    }
    

    Notice that every if has 1 less condition to check in your case.