else 关键字

概述

else 关键字用于if语句的条件分支,当if条件为false时执行else块中的代码。

语法格式

if (条件) {
    // 条件为true时执行
} else {
    // 条件为false时执行
}

// else if链
if (条件1) {
    // 条件1为true
} else if (条件2) {
    // 条件2为true
} else {
    // 所有条件都为false
}

基本用法

public class ElseExample {
    public static void main(String[] args) {
        // 简单的if-else
        int number = 15;

        if (number % 2 == 0) {
            System.out.println(number + " 是偶数");
        } else {
            System.out.println(number + " 是奇数");
        }

        // 年龄判断
        int age = 20;

        if (age >= 18) {
            System.out.println("已成年");
        } else {
            System.out.println("未成年");
        }

        // 成绩等级判断
        int score = 85;

        if (score >= 90) {
            System.out.println("优秀");
        } else if (score >= 80) {
            System.out.println("良好");
        } else if (score >= 70) {
            System.out.println("中等");
        } else if (score >= 60) {
            System.out.println("及格");
        } else {
            System.out.println("不及格");
        }
    }
}

复杂条件处理

public class ComplexElseExample {

    // 用户登录验证
    public static void validateLogin(String username, String password) {
        if (username == null || username.trim().isEmpty()) {
            System.out.println("用户名不能为空");
        } else if (password == null || password.length() < 6) {
            System.out.println("密码不能为空且长度至少6位");
        } else if (username.equals("admin") && password.equals("admin123")) {
            System.out.println("管理员登录成功");
        } else if (isValidUser(username, password)) {
            System.out.println("普通用户登录成功:" + username);
        } else {
            System.out.println("用户名或密码错误");
        }
    }

    private static boolean isValidUser(String username, String password) {
        // 模拟用户验证
        return username.length() >= 3 && password.length() >= 6;
    }

    // 文件类型判断
    public static void processFile(String filename) {
        if (filename == null) {
            System.out.println("文件名不能为null");
        } else if (filename.trim().isEmpty()) {
            System.out.println("文件名不能为空");
        } else if (filename.endsWith(".txt")) {
            System.out.println("处理文本文件: " + filename);
        } else if (filename.endsWith(".jpg") || filename.endsWith(".png")) {
            System.out.println("处理图片文件: " + filename);
        } else if (filename.endsWith(".pdf")) {
            System.out.println("处理PDF文件: " + filename);
        } else {
            System.out.println("不支持的文件类型: " + filename);
        }
    }

    // 数字范围分类
    public static void classifyNumber(double number) {
        if (number > 0) {
            if (number < 1) {
                System.out.println("小正数: " + number);
            } else if (number <= 100) {
                System.out.println("中等正数: " + number);
            } else {
                System.out.println("大正数: " + number);
            }
        } else if (number < 0) {
            if (number > -1) {
                System.out.println("小负数: " + number);
            } else if (number >= -100) {
                System.out.println("中等负数: " + number);
            } else {
                System.out.println("大负数: " + number);
            }
        } else {
            System.out.println("零: " + number);
        }
    }

    public static void main(String[] args) {
        System.out.println("=== 登录验证 ===");
        validateLogin("admin", "admin123");
        validateLogin("user", "123456");
        validateLogin("", "password");

        System.out.println("\n=== 文件处理 ===");
        processFile("document.txt");
        processFile("photo.jpg");
        processFile("report.pdf");
        processFile("script.js");

        System.out.println("\n=== 数字分类 ===");
        classifyNumber(0.5);
        classifyNumber(50);
        classifyNumber(150);
        classifyNumber(-0.3);
        classifyNumber(-50);
        classifyNumber(0);
    }
}

实际应用示例

import java.util.*;

public class ElseApplications {

    // 银行账户操作
    public static class BankAccount {
        private double balance;
        private boolean isActive;

        public BankAccount(double initialBalance) {
            this.balance = initialBalance;
            this.isActive = true;
        }

        public void withdraw(double amount) {
            if (!isActive) {
                System.out.println("账户已被冻结,无法取款");
            } else if (amount <= 0) {
                System.out.println("取款金额必须大于0");
            } else if (amount > balance) {
                System.out.println("余额不足,当前余额: " + balance);
            } else {
                balance -= amount;
                System.out.println("取款成功: " + amount + ",余额: " + balance);
            }
        }

        public void deposit(double amount) {
            if (!isActive) {
                System.out.println("账户已被冻结,无法存款");
            } else if (amount <= 0) {
                System.out.println("存款金额必须大于0");
            } else {
                balance += amount;
                System.out.println("存款成功: " + amount + ",余额: " + balance);
            }
        }

        public void setActive(boolean active) {
            this.isActive = active;
        }

        public double getBalance() {
            return balance;
        }
    }

    // 学生成绩管理
    public static void evaluateStudent(String name, int[] scores) {
        if (name == null || name.trim().isEmpty()) {
            System.out.println("学生姓名不能为空");
            return;
        }

        if (scores == null || scores.length == 0) {
            System.out.println("成绩数据为空");
            return;
        }

        double average = calculateAverage(scores);

        System.out.println("学生: " + name);
        System.out.println("各科成绩: " + Arrays.toString(scores));
        System.out.println("平均分: " + String.format("%.2f", average));

        if (average >= 90) {
            System.out.println("等级: 优秀");
        } else if (average >= 80) {
            System.out.println("等级: 良好");
        } else if (average >= 70) {
            System.out.println("等级: 中等");
        } else if (average >= 60) {
            System.out.println("等级: 及格");
        } else {
            System.out.println("等级: 不及格");
        }

        // 额外判断
        if (hasFailingGrade(scores)) {
            System.out.println("警告: 存在不及格科目");
        } else {
            System.out.println("所有科目均及格");
        }
    }

    private static double calculateAverage(int[] scores) {
        int sum = 0;
        for (int score : scores) {
            sum += score;
        }
        return (double) sum / scores.length;
    }

    private static boolean hasFailingGrade(int[] scores) {
        for (int score : scores) {
            if (score < 60) {
                return true;
            }
        }
        return false;
    }

    // 购物车结算
    public static void processOrder(List<String> items, double totalAmount, String paymentMethod) {
        if (items == null || items.isEmpty()) {
            System.out.println("购物车为空,无法结算");
        } else if (totalAmount <= 0) {
            System.out.println("订单金额无效");
        } else if (paymentMethod == null || paymentMethod.trim().isEmpty()) {
            System.out.println("请选择支付方式");
        } else {
            System.out.println("订单商品: " + items);
            System.out.println("订单金额: " + totalAmount);

            if (paymentMethod.equals("credit")) {
                if (totalAmount > 10000) {
                    System.out.println("信用卡支付金额过大,需要验证");
                } else {
                    System.out.println("信用卡支付成功");
                }
            } else if (paymentMethod.equals("debit")) {
                System.out.println("借记卡支付成功");
            } else if (paymentMethod.equals("cash")) {
                if (totalAmount > 5000) {
                    System.out.println("现金支付金额过大,建议使用银行卡");
                } else {
                    System.out.println("现金支付成功");
                }
            } else {
                System.out.println("不支持的支付方式: " + paymentMethod);
            }
        }
    }

    public static void main(String[] args) {
        // 银行账户测试
        System.out.println("=== 银行账户操作 ===");
        BankAccount account = new BankAccount(1000);
        account.withdraw(500);
        account.withdraw(600);
        account.deposit(200);
        account.setActive(false);
        account.withdraw(100);

        // 学生成绩测试
        System.out.println("\n=== 学生成绩评估 ===");
        evaluateStudent("张三", new int[]{85, 92, 78, 90});
        evaluateStudent("李四", new int[]{65, 58, 72, 69});
        evaluateStudent("", new int[]{90, 85});

        // 购物车测试
        System.out.println("\n=== 购物车结算 ===");
        List<String> items1 = Arrays.asList("笔记本电脑", "鼠标", "键盘");
        processOrder(items1, 8999, "credit");

        List<String> items2 = Arrays.asList("咖啡", "面包");
        processOrder(items2, 25.5, "cash");

        processOrder(null, 100, "debit");
    }
}

三元运算符替代

public class TernaryOperatorExample {

    public static void compareIfElseWithTernary() {
        int a = 10, b = 20;

        // 使用if-else
        String result1;
        if (a > b) {
            result1 = "a更大";
        } else {
            result1 = "b更大或相等";
        }
        System.out.println("if-else结果: " + result1);

        // 使用三元运算符
        String result2 = (a > b) ? "a更大" : "b更大或相等";
        System.out.println("三元运算符结果: " + result2);

        // 复杂条件的比较
        int score = 85;

        // if-else方式
        String grade1;
        if (score >= 90) {
            grade1 = "A";
        } else if (score >= 80) {
            grade1 = "B";
        } else if (score >= 70) {
            grade1 = "C";
        } else {
            grade1 = "D";
        }
        System.out.println("if-else等级: " + grade1);

        // 嵌套三元运算符(不推荐,可读性差)
        String grade2 = (score >= 90) ? "A" : 
                        (score >= 80) ? "B" : 
                        (score >= 70) ? "C" : "D";
        System.out.println("三元运算符等级: " + grade2);
    }

    // 适合使用三元运算符的场景
    public static void goodTernaryUsage() {
        int[] numbers = {1, 2, 3, 4, 5};

        // 简单的条件赋值
        for (int num : numbers) {
            String type = (num % 2 == 0) ? "偶数" : "奇数";
            System.out.println(num + " 是 " + type);
        }

        // 方法参数中的条件
        String name = null;
        System.out.println("欢迎 " + (name != null ? name : "游客"));

        // 返回值的条件
        int value = -5;
        int absValue = (value >= 0) ? value : -value;
        System.out.println("绝对值: " + absValue);
    }

    // 应该使用if-else的场景
    public static void shouldUseIfElse() {
        int temperature = 25;

        // 多行代码处理 - 应该使用if-else
        if (temperature > 30) {
            System.out.println("天气很热");
            System.out.println("建议开空调");
            System.out.println("多喝水");
        } else if (temperature > 20) {
            System.out.println("天气适宜");
            System.out.println("可以外出活动");
        } else {
            System.out.println("天气较冷");
            System.out.println("注意保暖");
        }
    }

    public static void main(String[] args) {
        System.out.println("=== if-else与三元运算符比较 ===");
        compareIfElseWithTernary();

        System.out.println("\n=== 适合三元运算符的场景 ===");
        goodTernaryUsage();

        System.out.println("\n=== 应该使用if-else的场景 ===");
        shouldUseIfElse();
    }
}

错误处理和边界情况

import java.util.*;

public class ElseErrorHandling {

    // 安全的数组访问
    public static void safeArrayAccess(int[] array, int index) {
        if (array == null) {
            System.out.println("数组为null");
        } else if (index < 0) {
            System.out.println("索引不能为负数: " + index);
        } else if (index >= array.length) {
            System.out.println("索引超出范围: " + index + ",数组长度: " + array.length);
        } else {
            System.out.println("array[" + index + "] = " + array[index]);
        }
    }

    // 安全的除法运算
    public static void safeDivision(double dividend, double divisor) {
        if (divisor == 0) {
            System.out.println("除数不能为0");
        } else if (Double.isNaN(dividend) || Double.isNaN(divisor)) {
            System.out.println("参数不能为NaN");
        } else if (Double.isInfinite(dividend) || Double.isInfinite(divisor)) {
            System.out.println("参数不能为无穷大");
        } else {
            double result = dividend / divisor;
            System.out.println(dividend + " / " + divisor + " = " + result);
        }
    }

    // 字符串处理
    public static void processString(String input) {
        if (input == null) {
            System.out.println("输入字符串为null");
        } else if (input.isEmpty()) {
            System.out.println("输入字符串为空");
        } else if (input.trim().isEmpty()) {
            System.out.println("输入字符串只包含空白字符");
        } else if (input.length() < 3) {
            System.out.println("字符串太短: " + input);
        } else if (input.length() > 50) {
            System.out.println("字符串太长,截取前50个字符: " + input.substring(0, 50));
        } else {
            System.out.println("处理字符串: " + input.trim().toUpperCase());
        }
    }

    // 集合操作
    public static void processCollection(List<Integer> list) {
        if (list == null) {
            System.out.println("集合为null");
        } else if (list.isEmpty()) {
            System.out.println("集合为空");
        } else if (list.size() == 1) {
            System.out.println("集合只有一个元素: " + list.get(0));
        } else {
            int sum = 0;
            int count = 0;

            for (Integer num : list) {
                if (num != null) {
                    sum += num;
                    count++;
                }
            }

            if (count == 0) {
                System.out.println("集合中没有有效数字");
            } else {
                double average = (double) sum / count;
                System.out.println("集合大小: " + list.size());
                System.out.println("有效数字: " + count);
                System.out.println("总和: " + sum);
                System.out.println("平均值: " + String.format("%.2f", average));
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("=== 安全数组访问 ===");
        int[] arr = {1, 2, 3, 4, 5};
        safeArrayAccess(arr, 2);
        safeArrayAccess(arr, -1);
        safeArrayAccess(arr, 10);
        safeArrayAccess(null, 0);

        System.out.println("\n=== 安全除法运算 ===");
        safeDivision(10, 2);
        safeDivision(10, 0);
        safeDivision(Double.NaN, 2);
        safeDivision(10, Double.POSITIVE_INFINITY);

        System.out.println("\n=== 字符串处理 ===");
        processString("Hello World");
        processString("");
        processString("   ");
        processString("Hi");
        processString(null);

        System.out.println("\n=== 集合操作 ===");
        processCollection(Arrays.asList(1, 2, 3, 4, 5));
        processCollection(Arrays.asList(10));
        processCollection(new ArrayList<>());
        processCollection(Arrays.asList(1, null, 3, null, 5));
        processCollection(null);
    }
}

最佳实践

public class ElseBestPractices {

    // 1. 避免过深的嵌套
    public static void avoidDeepNesting(String input) {
        // 不好的做法 - 深层嵌套
        /*
        if (input != null) {
            if (!input.isEmpty()) {
                if (input.length() >= 3) {
                    if (input.matches("[a-zA-Z]+")) {
                        System.out.println("有效输入: " + input);
                    } else {
                        System.out.println("只能包含字母");
                    }
                } else {
                    System.out.println("长度至少3个字符");
                }
            } else {
                System.out.println("不能为空字符串");
            }
        } else {
            System.out.println("不能为null");
        }
        */

        // 好的做法 - 早期返回
        if (input == null) {
            System.out.println("不能为null");
            return;
        }

        if (input.isEmpty()) {
            System.out.println("不能为空字符串");
            return;
        }

        if (input.length() < 3) {
            System.out.println("长度至少3个字符");
            return;
        }

        if (!input.matches("[a-zA-Z]+")) {
            System.out.println("只能包含字母");
            return;
        }

        System.out.println("有效输入: " + input);
    }

    // 2. 使用卫语句(Guard Clauses)
    public static void processUser(String name, int age, String email) {
        // 卫语句处理无效情况
        if (name == null || name.trim().isEmpty()) {
            System.out.println("姓名不能为空");
            return;
        }

        if (age < 0 || age > 150) {
            System.out.println("年龄无效: " + age);
            return;
        }

        if (email == null || !email.contains("@")) {
            System.out.println("邮箱格式无效");
            return;
        }

        // 主要业务逻辑
        System.out.println("处理用户:");
        System.out.println("姓名: " + name.trim());
        System.out.println("年龄: " + age);
        System.out.println("邮箱: " + email);

        if (age >= 18) {
            System.out.println("状态: 成年用户");
        } else {
            System.out.println("状态: 未成年用户");
        }
    }

    // 3. 合理的条件分组
    public static void categorizeScore(int score) {
        if (score < 0 || score > 100) {
            System.out.println("分数无效: " + score);
        } else if (score >= 90) {
            System.out.println("优秀: " + score);
        } else if (score >= 80) {
            System.out.println("良好: " + score);
        } else if (score >= 70) {
            System.out.println("中等: " + score);
        } else if (score >= 60) {
            System.out.println("及格: " + score);
        } else {
            System.out.println("不及格: " + score);
        }
    }

    // 4. 明确的else含义
    public static void processPayment(double amount, String currency) {
        if (amount <= 0) {
            System.out.println("金额必须大于0");
        } else if (currency == null || currency.trim().isEmpty()) {
            System.out.println("币种不能为空");
        } else if (currency.equals("USD")) {
            System.out.println("处理美元支付: $" + amount);
        } else if (currency.equals("EUR")) {
            System.out.println("处理欧元支付: €" + amount);
        } else if (currency.equals("CNY")) {
            System.out.println("处理人民币支付: ¥" + amount);
        } else {
            // 明确的else - 处理其他币种
            System.out.println("处理其他币种支付: " + amount + " " + currency);
        }
    }

    public static void main(String[] args) {
        System.out.println("=== 避免深层嵌套 ===");
        avoidDeepNesting("hello");
        avoidDeepNesting("hi");
        avoidDeepNesting("");
        avoidDeepNesting(null);

        System.out.println("\n=== 卫语句使用 ===");
        processUser("张三", 25, "zhangsan@example.com");
        processUser("", 25, "email@test.com");
        processUser("李四", -5, "lisi@example.com");

        System.out.println("\n=== 条件分组 ===");
        categorizeScore(95);
        categorizeScore(75);
        categorizeScore(55);
        categorizeScore(105);

        System.out.println("\n=== 明确的else含义 ===");
        processPayment(100, "USD");
        processPayment(200, "JPY");
        processPayment(-50, "CNY");
    }
}

else关键字是Java条件控制的重要组成部分,合理使用能让代码逻辑更清晰、更健壮。

powered by Gitbook© 2025 编外计划 | 最后修改: 2025-07-28 16:25:54

results matching ""

    No results matching ""