开发者

Question on ifs

I have the following code:

     boolean Short = x();
    boolean Long = y();       
    boolean Longer = z();

    if 开发者_开发百科(Short )
        return "abc";

    if (Long)
        return "def";

    if (Longer) 
        return "ghi";        

The three bool methods (x, y, z) all do maths on value. I need an additional if statement to return the number from if the above 3 ifs are not evaluated to true. How could this be done and are there any redundant ifs? Also, what do I need to know about precedence with ifs? My name says "dotnet" but I am equally a programmer in Java (I've spent time trying to pick it up as much as .NET).

Thanks


It's fine, but you do not need another if:

boolean Short = x();
boolean Long = y();       
boolean Longer = z();

if (Short )
    return "abc";

if (Long)
    return "def";

if (Longer) 
    return "ghi"; 

return "none of the above";

The if statements will evaluate in order, once one of them is true, the return statement will end execution within the method, so nothing after it will be evaluated.

If none of them are true, the last return will end execution.

You could substitute the variables with the calls themselves if you do not need to evaluate y() and z() when x() is true, nor z() if y() is true:

if (x())
    return "abc";

if (y())
    return "def";

if (z()) 
    return "ghi"; 

return "none of the above";


There are no redundant if's. You just need an extra return in case none of the three conditions evaluate to true. You can also add else clauses if you want.

boolean Short = x();
boolean Long = y();       
boolean Longer = z();

if (Short )
    return "abc";
else if (Long)
    return "def";
else if (Longer) 
    return "ghi";
else
    return "something else";

Or, if the methods x(), y(), z() have no side effects:

if (x())
    return "abc";
else if (y())
    return "def";
else if (z()) 
    return "ghi";
else
    return "something else";

Also, you can use the ? operator for a more compact, but perhaps more cryptic syntax:

return x()? "abc" :
       y()? "def" :
       z()? "ghi" :
       "something else";

But ifs are probably more readable than this :-)


Just put:

boolean Short = x();
boolean Long = y();       
boolean Longer = z();

if (Short )
    return "abc";

if (Long)
    return "def";

if (Longer) 
    return "ghi";

return "xyz";


Hm.. Probably this

if (x())
    return "abc";

if (y())
    return "def";

if (z()) 
    return "ghi"; 
return "smt"; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜