三元运算符

格式

x ? y : z

解释

如果x==true,则结果为y,反之为z;

代码演示

   //三元运算符
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入成绩");
        if (scanner.hasNextInt()) {
            int score = scanner.nextInt();
            if (score >= 0) {
                String type = score >= 60 ? "及格" : "不及格";
                System.out.println(type);
            } else {
                System.out.println("请输入正确的成绩");
            }
        } else {
            System.out.println("输入的成绩不合法");
        }
        scanner.close();
    }

小结

三元运算符与if条件运算符相比,显得更加精简,便于理解和美观。

posted @ 2020-07-15 15:52  大酷仔  阅读(196)  评论(0编辑  收藏  举报