简体   繁体   English

如何简化 java 中的 if-else 语句?

[英]How can I simplify my if-else statement in java?

In my code I have a method size(MyData) that returns size of data - it can be 0 or greater.在我的代码中,我有一个返回数据大小的方法size(MyData) - 它可以是 0 或更大。 I also have a flag exclude that can be true or false .我还有一个exclude标志,可以是truefalse The point of my algorithm is to do some operation on data based on its size and the value of the flag.我的算法的要点是根据数据的大小和标志的值对数据进行一些操作。

  • If the size is greater than 0, I want to do operation on data.如果大小大于0,我想对数据进行操作。

  • If the size is 0, then I need to check the value of the flag excluded .如果大小为 0,那么我需要检查标志excluded的值。 In that case, if the flag excluded is set to true, I don't want to do operation on data.在那种情况下,如果excluded标志设置为真,我不想对数据进行操作。 But if the flag is set to false, I need to do operation on data.但是如果标志设置为false,我需要对数据进行操作。

This is my algorithm so far:到目前为止,这是我的算法:

int numberOfKids = size(MyData); //this can be 0 or greater
if (numberOfKids != 0) {
    //do operation
}
else {
    if (!exclude) {
        //do operation
    }
}

is there a better way of writing this algorithm?有没有更好的方法来编写这个算法? Thanks!谢谢!

Assuming it's the same operation:假设它是相同的操作:

int numberOfKids = size(MyData); //this can be 0 or greater
if (numberOfKids != 0 || !exclude) {
    //do operation
}

The || || comparison works by evaluating the left side, and if it is true, the right side is skipped.比较通过评估左侧进行,如果为真,则跳过右侧。 But if the left side is false, then the right side is evaluated.但如果左侧为假,则评估右侧。

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

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