java 三元表達式

eg1:

static int demo01 (int a , int b ){
    int c = a > b ? 0 :1;
    return c;
}
public static void main(String[] args) {
    demo01(1,3);
}

eg2:(三元表達式和if else的轉換)

static int demo02 (int i ){
    return i <10 ? i*10 : i*100;
}
public static void main(String[] args) {
    demo02(20);
}

轉換成if else結構:

static int demo03 (int i ){
   if(i < 10){
       return i*10;
   }else {
       return i*100;
   }
}
public static void main(String[] args) {
    demo03(20);
}

注意:上面的例子都沒有寫輸出語句,請小白們自行加上輸入語句打印結果。

總結:

表達式:

            boolen-exp ? value1 : value2;【(條件表達式)?表達式1:表達式2;】

運算規則:

            a:判斷條件表達式(boolean-exp),返回的結果是一個布爾值;

            b:如果“布爾表達式”的結果爲true,那麼運算結果爲表達式1;

            c:如果“布爾表達式”的結果爲false,那麼運算結果爲表達式2;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章