简体   繁体   English

简化或减少 if 语句

[英]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??我想通过用开关或 function 替换它们来减少 If 的数量,这可能吗? 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.由于我的代码太长,我认为 function 可以比重复的 if 或 else 做得更好,而且它也更容易理解。

 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):您始终可以使用循环(或 stream,具体取决于性能要求):

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).请注意,如果其中两个值相同且为最大值(例如 a=16、b=16、c=12、d=9),则当前代码的行为不明确。 The output is "detector 1", but "detector 2" is also the max. output 是“检测器 1”,但“检测器 2”也是最大值。

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).如果您的列表可以包含多个最大值并且您想找到所有最大值,则需要稍微更改循环(但您现有的代码只找到“第一个”值的 position)。

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.将使用任意数量的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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