mercredi 25 septembre 2019

what is the difference between these java codes with if-else ? : operator

class Rextester
{  
    public static void main(String[] args) {
        int maxArray = 0;
        int minArray = 0;
        Scanner input = new Scanner(System.in);
        int[] numArray = new int[300];
        for (int i = 0 ; i < 4 ; i++){
            int num = input.nextInt();
            if(maxArray>num){
                maxArray=maxArray;
            }else{
                maxArray=num;
            }
             if(minArray<num){
                minArray=minArray;
            }else{
                minArray=num;
            }



    }
         System.out.println(maxArray+" "+minArray);

}
}

*second code*


public class Mshmaxminarray {


    public static void main(String[] args) {
        int maxArray = 0;
        int minArray = 0;
        Scanner input = new Scanner(System.in);
        int[] numArray = new int[300];
        for (int i = 0 ; i < 300 ; i++){
            int num = input.nextInt();
            maxArray = maxArray > num ? maxArray : num ;
            minArray = minArray < num ? minArray : num ;
        }
        System.out.println(maxArray+" "+minArray);

    }

}

can anyone tell me why the above two codes give different solution. Highest is fine but minArray gives wrong solution. isn't "condition ? if : else" same as if and else? i am trying to find highest and minimum number of array , both gives the highest but there is some problem with minimum. if both are same why different solution? and if not what is the difference?

Aucun commentaire:

Enregistrer un commentaire