【java】三元表达式

在Java中,三元表达式(也称为三元运算符)是一种简洁的条件运算符,用来替代简单的 if-else 语句。其语法形式为:

condition ? expression1 : expression2;

其中,condition 是一个布尔表达式。如果 conditiontrue,则整个三元表达式的值为 expression1;否则,值为 expression2

以下是一些示例代码,展示了如何在Java中使用三元表达式:

示例1:基本使用

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int a = 10;
        int b = 20;

        // 使用三元表达式找出较大的值
        int max = (a > b) ? a : b;

        System.out.println("The maximum value is: " + max);
    }
}

在这个例子中,a > b 是条件表达式。如果 a 大于 b,则 max 的值为 a;否则,max 的值为 b

示例2:嵌套三元表达式

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int a = 10;
        int b = 20;
        int c = 30;

        // 使用嵌套三元表达式找出三个数中的最大值
        int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);

        System.out.println("The maximum value is: " + max);
    }
}

在这个例子中,嵌套的三元表达式用于找出 a, b, c 三个数中的最大值。

示例3:三元表达式与字符串

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int score = 85;

        // 使用三元表达式判断成绩是否及格
        String result = (score >= 60) ? "Pass" : "Fail";

        System.out.println("The result is: " + result);
    }
}

在这个例子中,根据 score 的值判断是否及格,并返回相应的字符串。

示例4:三元表达式返回布尔值

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int age = 18;

        // 使用三元表达式判断是否成年
        boolean isAdult = (age >= 18) ? true : false;

        System.out.println("Is adult: " + isAdult);
    }
}

在这个例子中,三元表达式用于判断一个人是否成年。

这些示例展示了三元表达式在Java中的基本用法。它们可以使代码更加简洁和易读,但在使用嵌套三元表达式时要注意可读性。

猜你喜欢

转载自blog.csdn.net/qq_45687669/article/details/143482654