条件的顺序是否影响其他陈述? [英] does order of the conditions matter on if else statement?

查看:67
本文介绍了条件的顺序是否影响其他陈述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编码bat Logic-2上,我在下面列出的第一个方法中输入了loneSum问题.对于所有测试,只有一个测试是正确的.它唯一失败的是所有变量都等于同一整数.但是,当我在网上查找解决方案时,我得到了下面列出的第二种方法,并且有效.我认为我的方法与正确的解决方案之间的唯一区别是其他if(a == b&& b == c){return 0;}"的位置.我的问题是条件的顺序对如果不是"语句有影响吗? (我对此表示歉意,英语不是我的母语.谢谢.)

On coding bat Logic-2, loneSum problem I typed in the first method listed below. It was right for all of the tests except for only one. The only one it failed on was where all of the variables equaled to the same integer. But when I looked up for the solution online I got the second method listed below and that worked. I think the only difference between my method and the right solution was the position of the "else if(a==b && b==c){return 0;}". My question is does the order of the conditions matter on the "if else" statements? (I apologize in advance for the wording, English is not my first language. Thank You.)

 public int loneSum(int a, int b, int c) {
      int sum = a + b + c;
      if(a==b)
      {return c;}
      else if(b==c)
      {return a;}
      else if(c==a)
      {return b;}
      else if(a==b && b==c)
      {return 0;}
      else
      return sum;
    }

public int loneSum(int a, int b, int c) {
  int sum = a + b + c;

if(a==b && b==c)
  {return 0;}
  else if(b==c)
  {return a;}
  else if(c==a)
  {return b;}
  else if(a==b)
  {return c;}
  else
  return sum;
}

推荐答案

简单的示例,两个相同的方法,只是if else语句的顺序不同:

Simple sample, 2 same methods, only different order of the if else statements:

String method1(int input) {
    if (input > 1) {
        return "Foo";
    } else if (input > 5) {
        return "Bar";
    }
    return "Baz";
}

String method2(int input) {
    if (input > 5) {
        return "Bar";
    } else if (input > 1) {
        return "Foo";
    }
    return "Baz";
}

用输入调用两个方法,假设为9.您认为它们会返回相同的字符串吗?

Call both methods with an input, lets say 9. Do you think they'll return the same string?

这篇关于条件的顺序是否影响其他陈述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆