Search code examples
javaclassif-statementnumbersnested-if

How to do nested if - else with 4 numbers to find biggest number


public class NastingIfElse {

    public static void main(String[] args) {

        int a = 998 , b = 857 , c = 241 , d = 153;
        int result;

        if ( a > b ) {
            if ( a > c ) {
                if ( a > d ) {
                    result = a;
                }else {
                    result = d;
                }
            }
        }
        if ( b > c ) {
            if ( b > d ) {
                result = b;
            }else {
                result = d;
            }
        }
        if ( c > a ) {
            if ( c > d ) {
                result = c;
            }else {
                result = d;
            }
        }
        if ( d > a ) {
            if ( d > c ) {
                if ( d > b ) {
                    result = d;
                }else {
                    result = b;
                }
            }
        }



        System.out.println("Biggest number of three is " + result);


    }

}

I want to do this code and find out the biggest number from this 4 numbers. but have some problems with this "nesting if program". so I need to find out some way to run this particular program for finding the highest number from these numbers by only using "nested if".

so help me in this program.


Solution

  • if it is some kind of practice which must be done by nested if and elses, try this:

        int a = 998 , b = 857 , c = 241 , d = 153;
        int result;
    
        if ( a > b ) {
            if ( a > c ) {
                if ( a > d ) {
                    result = a;
                }
                else {
                    result = d;
                }
            }
            else if ( c > d ) {
                result = c;
            }
            else {
                result = d;
            }
        }
        else if ( b > c ) {
            if ( b > d ) {
                result = b;
            }
            else {
                result = d;
            }
        }
        else if ( c > d ) {
            result = c;
        }
        else {
            result = d;
        }
    

    otherwise there are really better options in java, with supporting more count of numbers.