简体   繁体   中英

Simplify or reduce if statement

I want to reduce the number of If by replacing them by a switch or a function is it possible?? since my code is too long I think a function can do the job better than a repetitive if or else and It will also be more understandable.

 double a = text.charAt(39), b= text.charAt(40), c= text.charAt(41), d= text.charAt(42) ;
       Collection<Double> list=new ArrayList<Double>();
        list.add(a);
        list.add(b);
        list.add(c);
        list.add(d);
        if ( a>=15||b>=15||c>=15||d>=15) {
            if (  Collections.max(list) == a) {
                Defauts_detecteur.setText("Défauts récurrents constatés sur le détecteur 1");
            }
            else if ( Collections.max(list) == b)
            {
                Defauts_detecteur.setText("Défauts récurrents constatés sur le détecteur 2");
            }
            else if ( Collections.max(list) == c )
            {
                Defauts_detecteur.setText("Défauts récurrents constatés sur le détecteur 3");
            }
            else
            {
                Defauts_detecteur.setText("Défauts récurrents constatés sur le détecteur 4");
            }

            Conseil_detecteur.setText("--> Par mesure de sécurité, nous vous conseillons vivement de vérifier que le détecteur est bien collé au produit à sécuriser.\nPour une adhésion optimale, remplacez l’adhésif.\nVérifiez que le détecteur est bien connecté à la centrale et qu’il est en bon état.");

        }
        else {
            Conseil_detecteur.setText("--> Des alarmes régulières ? Envie d'en savoir plus ?\nContactez notre hotliner au 02 37 33 69 66 qui vous guidera dans leurs résolutions.");
            Defauts_detecteur.setVisibility(View.GONE);
        }

You can always use a loop (or a stream, depending on performance requirements):

final double a = text.charAt(39), b = text.charAt(40), c = text.charAt(41), d = text.charAt(42) ;
final List<Double> list = Arrays.asList(a, b, c, d); // note that an array (double[]) instead of a collection would avoid boxing

final double maxValue = Collections.max(list);
if (maxValue >= 15) { // at least one value is greater than or equal to 15, no need to inspect each element individually
   for (int i = 0; i < list.size(); ++i) {
      if (list.get(i) == maxValue) {
        Defauts_detecteur.setText("Défauts récurrents constatés sur le détecteur " + (i+1));
        break; // stop after first matching value was found
      }
   }

   Conseil_detecteur.setText("--> Par mesure de sécurité, nous vous conseillons vivement de vérifier que le détecteur est bien collé au produit à sécuriser.\nPour une adhésion optimale, remplacez l’adhésif.\nVérifiez que le détecteur est bien connecté à la centrale et qu’il est en bon état.");
} else {
   Conseil_detecteur.setText("--> Des alarmes régulières ? Envie d'en savoir plus ?\nContactez notre hotliner au 02 37 33 69 66 qui vous guidera dans leurs résolutions.");
   Defauts_detecteur.setVisibility(View.GONE);
}

Note that your current code has unclear behavior if two of the values are identical and max (eg a=16, b=16, c=12, d=9). The output is "detector 1", but "detector 2" is also the max.

If you your list can contain multiple max values and you want to find all of them, you need to slightly alter your loop (but your existing code only found the position of "first" value).

final List<Integer> maxPositions = new ArrayList<>();
for (int i = 0; i < list.size(); ++i) {
  if (list.get(i) == maxValue) {
    maxPositions.add(i+1);
    // don't stop, keep going
  }
}

// will print e.g. "found at positions [1, 4]
….setText("Max values found at positions " + maxPositions);

Functional style:

    HashMap<Character, Integer> values = new HashMap<>();
    values.put('a', 239);
    values.put('b', 123);
    values.put('c', 345);
    values.put('d', 555);

    Optional<Map.Entry<Character, Integer>> max = values.entrySet().stream().filter(e -> e.getValue() > 15).max(Map.Entry.comparingByValue());
    max.ifPresent(characterIntegerEntry -> System.out.println(" max entry value for detector " + characterIntegerEntry.getKey() + " is" + characterIntegerEntry.getValue()));

will work with arbitrary amount of data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM