簡體   English   中英

如何將if-else簡化為一個語句?

[英]How can I simplify this if-else into one statement?

如何將以下代碼簡化為一行(沒有if-else語句)?

public static void main(String[] args) 
{
    boolean result;
    boolean a = false;
    boolean b = false;
    boolean isEmpty = false;
    if (a) {
        result = isEmpty && !b;
        System.out.println("if  " + (isEmpty && !b));
    } else {
        System.out.println("else    " + !b);
        result = !b;
    }
    System.out.println(result);
}

如果atrue ,則必須檢查isEmpty AND !b是否為true 如果afalse (或者!atrue ),則足以檢查!b是否為true

因此,您可以使用以下命令替換if語句的邏輯:

result = !b && (isEmpty || !a);

您可以使用三元運算符:

result = a ? isEmpty && !b : !b;

我認為你正在尋找的是三元運算符

事實上,你可以用這樣的東西(但沒有println)總結if-else語句:

result = (a ? isEmpty && !b : !b); System.out.println(result + "\\n");

使用以下內容:

result = a ? isEmpty && !b : !b;

暫無
暫無

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

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