【问题标题】:If/Else Logical FlowIf/Else 逻辑流程
【发布时间】:2015-02-21 08:08:22
【问题描述】:

如果我有类似的东西:

if (n % 10 == 8 && (n/10) % 10 == 8) count = count + 2;
else if (n % 10 == 8) count++;

基本上,如果条件ab 成立,那么就做点什么。如果只有条件a 成立,请执行其他操作。最好的逻辑流程是什么?

【问题讨论】:

  • if(a) {if(b) something; else something;}?

标签: java if-statement logic


【解决方案1】:
// check the condition a
if (n % 10 == 8)
{
    // check the condition b
    if ((n/10) % 10 == 8))
    {
        count = count + 2;
    }
    // only condition a took place
    else
    {
        count++;
    }
}

【讨论】:

    【解决方案2】:

    为了尽可能缩短代码(尽管以可读性为代价),您可以使用 ternary op as

    count += (n % 10) == 8 ? ((n/10) % 10 == 8 ? 2 : 1) : 0;
    

    【讨论】:

      猜你喜欢
      • 2023-03-28
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 2011-03-24
      相关资源
      最近更新 更多