簡體   English   中英

有沒有更簡潔的方法在Java中編寫多個if語句

[英]Is there any cleaner way to write multiple if-statements in Java

我在Java中有一個if-else結構,如下所示:

                    if (A || B || C){
                        if (A){
                            //Do something
                        }
                        if (B){
                            //Do something
                        }
                        if (C){
                            //Do something
                        }
                    } else {
                        //Do something
                    }

我想知道是否有更清潔,更簡單的方法來替換它?

如果A,B和C是評估成本高的條件,則可以使用額外的標志來確保它們僅被評估一次:

boolean found = false;
if (A) {
    //Do something
    found = true;
}
if (B){
    //Do something
    found = true;
}
if (C){
    //Do something
    found = true;
}
if (!found) {
    //Do something
}

否則(即如果它們評價起來並不昂貴),我會保持現狀。

是。

if (A) {
  // do A
}
if (B) {
  // do B
}
if (C) {
  // do C
}
if (! (A || B || C)) {
  // do "neither A or B or C"
}

雖然我認為你有什么是好的,你可以這樣做:

boolean d = false;
if (d |= A) { ... }
if (d |= B) { ... }
if (d |= C) { ... }
if (!d) {
  // What to do if A..C are all false.
}

如果任何條件匹配,則將d設置為true( d代表“做某事”)。

還有一個可能的解決方案:

public class ABC {

    private static final Logger log = LoggerFactory.getLogger(ABC.class);

    @Test
    public void abc() {
        boolean A = true;
        boolean B = false;
        boolean C = true;

        boolean abcProcessed = false;

        abcProcessed |= process(A, () -> {
            // Do something for A
            log.debug("A");
        });
        abcProcessed |= process(B, () -> {
            // Do something for B
            log.debug("B");
        });
        abcProcessed |= process(C, () -> {
            // Do something for B
            log.debug("C");
        });

        if (!abcProcessed) {
            // Do something for !(A||B||C)
            log.debug("!(A||B||C)");
        }
    }

    private boolean process(boolean flag, DoSomethingInterface doSomethingInterface) {
        // check condition
        if (flag) {
            // execute code specific for condition
            doSomethingInterface.doSomething();
            // return true (processed)
            return true;
        }

        // return false (not processed)
        return false;
    }

    public interface DoSomethingInterface {

        // code specific for condition
        void doSomething();
    }
}

一個想法是將條件檢查和相關代碼移動到單獨的方法。

我認為你應該使用其他條件:

if(A){

}else if(B){

}else if(C){

}else if(D){

}

但是,如果你有許多條件,比如A,B,C等,那么你覺得你的程序邏輯有問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM