dimanche 19 septembre 2021

Simplify code finding the maximum and minimum of 5 inputs

import java.util.Scanner;
public class Demo {
   public static void main( String args[] ) {
       Scanner myInput = new Scanner( System.in );
       double a, b, c, d, e;
       a = myInput.nextDouble();
       b = myInput.nextDouble();
       c = myInput.nextDouble();
       d = myInput.nextDouble();
       e = myInput.nextDouble();

           //checks if a is max or min
           if (a > b && a > c && a > d && a > e) {
               System.out.println("a is max");
           } else if (a < b && a < c && a < d && a < e) {
               System.out.println("a is min");
           }

           //checks if b is max or min
           if (b > a && b > c && b > d && b > e) {
               System.out.println("b is max");
           } else if (b < a && b < c && b < d && b < e) {
               System.out.println("b is min");
           }

           //checks if c is max or min
           if (c > a && c > b && c > d && c > e) {
               System.out.println("c is max");
           } else if (c < a && c < b && c < d && c < e) {
               System.out.println("c is min");
           }

           //checks if d is max or min
           if (d > a && d > b && d > c && d > e) {
               System.out.println("d is max");
           } else if (d < a && d < b && d < c && d < e) {
               System.out.println("d is min");
           }

           //checks if e is max or min
           if (e > a && e > b && e > c && e > d) {
               System.out.println("e is max");
           } else if (e < a && e < b && e < c && e < d) {
               System.out.println("e is min");
           }

           //checks if the integers are different
           if (a == b || a == c || a == d || a == e || b == c || b == d || b == e || c == d || c == e || d == e)
               System.out.println("Identical integers detected");
   }
}

I am trying to find the maximum and minimum of 5 inputs. This code works perfectly but can it be simplified? It seems very excessive but I have only just started programming in Java so I haven't learnt much yet. I am also only allowed to use if statements. No loops.

Aucun commentaire:

Enregistrer un commentaire