简体   繁体   English

if else语句的编写方法

[英]Methods of writing if else statement

An if-else statement can be written using ternary operator for eg 可以使用三元运算符编写if-else语句,例如

output = (val>val2) ? "Condition is true" : "Condition is false";

Now consider 现在考虑

if(condition1){
   //do something
}else if(condition2){
   //do something 
}else if(condition3){
  //do something
}

How to write above code using ternary operator ? 如何使用三元运算符编写以上代码?

output = (condition1) ? 
          "First Case" : ((condition2) ?
          "Second Case" : ( (condition3) ? 
          "Third Case") : (...));

But keep in mind that in case, the number of conditions become more than 3, it will be a maintenance nightmare. 但是请记住,以防万一,条件数量超过3个,将是维护的噩梦。

尝试这个。

(a?w:(b?x:(c?y:z)))

Something in expanded form like this: 诸如此类的扩展形式:

X outputfn( ... )
{
  if(c1)      { return A; }
  else if(c2) { return B; }
  else        { return C; }
}

output = outputfn(...);

Can be translated into 可以翻译成

output = (c1)?A:((c2)?B:C);

But its pretty unreadable. 但是它非常不可读。

So I'd recommened extracting it into a function and using the function instead. 因此,我建议将其提取到一个函数中并改用该函数。

I think i get it. 我想我明白了。 You'll want something like: 您将需要类似:

output = (val>val3)?"First Case":(val>val2)?"Second Case":"Default Case";

You simply put subsequent ifs in the right-most clause of the expression. 您只需将后续if放在表达式的最右边子句中。 Note that there will always be a default case at the end. 请注意,最后总是会有默认情况。

Sure. 当然。

What you're trying to write is a ternary operator as an if else statement. 您要编写的是一个三元运算符,作为if else语句。

Well, let's logically deduce this. 好吧,让我们从逻辑上推论这一点。

output = (val>val2) ? "Code here when condition is true" : "Code here when condition is false";

What we're saying is the following 我们在说的是以下内容

if(val > val2)
{
    //code here when condition is true;
}
else
{
  //code here when condition is false;
}

That's it! 而已!

Happy Coding! 编码愉快! ;) ;)

I would format it this way: 我会这样格式化:

int result = condition1 ? 1
  : condition2 ? 2
  : condition3 ? 3
  : -1;

But I concur with other posters that nested ternary operators can be difficult to understand. 但是我同意其他海报,即嵌套三元运算符可能很难理解。

Why? 为什么? What you've written is perfectly clear, and using the ternary operator won't change the generated code. 您编写的内容非常清楚,使用三元运算符不会更改生成的代码。

output = (condition1) ? "Condition1 is true" : ((condition2) ?
      "Condition2 is true" : ( (condition3) ? 
      "Condition3 is true" : " all Condition are false"));

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

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