Skip to content

Java基础

单元1

任务4

1.16 顺序结构

java
/**
 * Java顺序结构示例
 * 演示Java程序的基本顺序执行流程
 */
public class SequenceStructureDemo {
    public static void main(String[] args) {
        // ========== 1. 基本的输入输出顺序 ==========
        System.out.println("========== 1. 基本输入输出 ==========");
        
        // 变量声明和初始化
        String name = "张三";
        int age = 20;
        double score = 85.5;
        
        // 顺序输出
        System.out.println("姓名:" + name);
        System.out.println("年龄:" + age);
        System.out.println("成绩:" + score);
        
        // ========== 2. 算术运算顺序 ==========
        System.out.println("\n========== 2. 算术运算 ==========");
        
        int a = 10;
        int b = 3;
        
        int sum = a + b;           // 加法
        int difference = a - b;     // 减法
        int product = a * b;        // 乘法
        int quotient = a / b;       // 除法(整数除法)
        int remainder = a % b;      // 取余
        
        System.out.println(a + " + " + b + " = " + sum);
        System.out.println(a + " - " + b + " = " + difference);
        System.out.println(a + " × " + b + " = " + product);
        System.out.println(a + " ÷ " + b + " = " + quotient);
        System.out.println(a + " % " + b + " = " + remainder);
        
        // ========== 3. 表达式计算顺序 ==========
        System.out.println("\n========== 3. 表达式计算 ==========");
        
        int result1 = 10 + 5 * 2;           // 先乘后加
        int result2 = (10 + 5) * 2;         // 先括号内,再乘
        int result3 = 20 - 5 + 3;            // 从左到右
        int result4 = 20 - (5 + 3);          // 先括号内
        
        System.out.println("10 + 5 × 2 = " + result1);
        System.out.println("(10 + 5) × 2 = " + result2);
        System.out.println("20 - 5 + 3 = " + result3);
        System.out.println("20 - (5 + 3) = " + result4);
        
        // ========== 4. 数据类型转换顺序 ==========
        System.out.println("\n========== 4. 数据类型转换 ==========");
        
        int intNum = 100;
        double doubleNum = intNum;           // 自动类型转换(小转大)
        
        double d1 = 95.8;
        int i1 = (int) d1;                   // 强制类型转换(大转小,会丢失精度)
        
        System.out.println("int转double: " + intNum + " → " + doubleNum);
        System.out.println("double转int: " + d1 + " → " + i1);
        
        // 混合运算时的类型转换
        int x = 5;
        double y = 2.5;
        double z = x + y;                     // int自动转换为double
        System.out.println("5 + 2.5 = " + z);
        
        // ========== 5. 字符串连接顺序 ==========
        System.out.println("\n========== 5. 字符串连接 ==========");
        
        String str1 = "Hello";
        String str2 = "World";
        int num = 2024;
        
        String message = str1 + " " + str2 + " " + num;
        System.out.println("连接结果:" + message);
        
        // 混合连接(注意运算顺序)
        System.out.println("字符串 + 数字: " + 10 + 20);      // 输出:1020
        System.out.println("先运算再连接: " + (10 + 20));     // 输出:30
        
        // ========== 6. 赋值运算顺序 ==========
        System.out.println("\n========== 6. 赋值运算 ==========");
        
        int m, n, p;
        m = n = p = 10;                        // 连续赋值(从右向左)
        System.out.println("m = " + m + ", n = " + n + ", p = " + p);
        
        // 复合赋值
        int q = 5;
        q += 3;                                 // 等价于 q = q + 3
        System.out.println("q += 3 的结果:" + q);
        
        // ========== 7. 方法调用顺序 ==========
        System.out.println("\n========== 7. 方法调用 ==========");
        
        // 顺序调用多个方法
        printHeader();
        printBody();
        printFooter();
        
        // ========== 8. 综合示例:学生成绩计算 ==========
        System.out.println("\n========== 8. 综合示例:学生成绩计算 ==========");
        
        // 输入数据
        String studentName = "李四";
        double chinese = 85.5;
        double math = 92.0;
        double english = 78.5;
        
        // 计算总分
        double totalScore = chinese + math + english;
        
        // 计算平均分
        double averageScore = totalScore / 3;
        
        // 判断是否及格(综合多个条件)
        boolean allPass = chinese >= 60 && math >= 60 && english >= 60;
        
        // 输出结果
        System.out.println("学生:" + studentName);
        System.out.println("语文:" + chinese);
        System.out.println("数学:" + math);
        System.out.println("英语:" + english);
        System.out.println("总分:" + totalScore);
        System.out.println("平均分:" + String.format("%.2f", averageScore));
        System.out.println("是否全部及格:" + (allPass ? "是" : "否"));
    }
    
    /**
     * 打印头部信息
     */
    public static void printHeader() {
        System.out.println("=== 程序开始 ===");
    }
    
    /**
     * 打印主体内容
     */
    public static void printBody() {
        System.out.println("正在执行主要功能...");
    }
    
    /**
     * 打印尾部信息
     */
    public static void printFooter() {
        System.out.println("=== 程序结束 ===");
    }
}

1.17 选择结构

java
import java.util.Scanner;

/**
 * Java选择结构示例
 * 演示if-else和switch语句的多种用法
 */
public class SelectionStructureDemo {
    public static void main(String[] args) {
        // 创建Scanner对象用于获取用户输入
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("========== Java选择结构学习示例 ==========");
        
        // ========== 1. 单分支if语句 ==========
        System.out.println("\n========== 1. 单分支if语句 ==========");
        
        System.out.print("请输入您的年龄:");
        int age = scanner.nextInt();
        
        if (age >= 18) {
            System.out.println("您已成年,可以进入网吧");
        }
        
        // ========== 2. 双分支if-else语句 ==========
        System.out.println("\n========== 2. 双分支if-else语句 ==========");
        
        System.out.print("请输入您的成绩:");
        int score = scanner.nextInt();
        
        if (score >= 60) {
            System.out.println("恭喜!考试及格!");
        } else {
            System.out.println("很遗憾,考试不及格,继续努力!");
        }
        
        // ========== 3. 多分支if-else if语句 ==========
        System.out.println("\n========== 3. 多分支if-else if语句 ==========");
        
        System.out.print("请输入您的考试分数(0-100):");
        int examScore = scanner.nextInt();
        
        if (examScore >= 90 && examScore <= 100) {
            System.out.println("等级:A(优秀)");
        } else if (examScore >= 80 && examScore < 90) {
            System.out.println("等级:B(良好)");
        } else if (examScore >= 70 && examScore < 80) {
            System.out.println("等级:C(中等)");
        } else if (examScore >= 60 && examScore < 70) {
            System.out.println("等级:D(及格)");
        } else if (examScore >= 0 && examScore < 60) {
            System.out.println("等级:E(不及格)");
        } else {
            System.out.println("输入错误!分数必须在0-100之间");
        }
        
        // ========== 4. 嵌套if语句 ==========
        System.out.println("\n========== 4. 嵌套if语句 ==========");
        
        System.out.print("请输入您的年龄:");
        int personAge = scanner.nextInt();
        
        if (personAge >= 0) {
            if (personAge < 18) {
                System.out.println("您是未成年人");
                if (personAge < 12) {
                    System.out.println("您还是儿童");
                } else {
                    System.out.println("您是青少年");
                }
            } else if (personAge < 60) {
                System.out.println("您是成年人");
                if (personAge >= 35) {
                    System.out.println("您已步入中年");
                }
            } else {
                System.out.println("您是老年人");
                if (personAge >= 80) {
                    System.out.println("您是长寿老人");
                }
            }
        } else {
            System.out.println("年龄不能为负数!");
        }
        
        // ========== 5. 条件运算符(三元运算符) ==========
        System.out.println("\n========== 5. 条件运算符 ==========");
        
        System.out.print("请输入一个整数:");
        int number = scanner.nextInt();
        
        // 使用if-else
        String result1;
        if (number % 2 == 0) {
            result1 = "偶数";
        } else {
            result1 = "奇数";
        }
        
        // 使用三元运算符(简洁版if-else)
        String result2 = (number % 2 == 0) ? "偶数" : "奇数";
        
        System.out.println("if-else判断:" + number + "是" + result1);
        System.out.println("三元运算符判断:" + number + "是" + result2);
        
        // 多个三元运算符嵌套
        String level = (number > 0) ? "正数" : (number < 0) ? "负数" : "零";
        System.out.println(number + "是" + level);
     
    }
}

1.18 switch分支语句结构

java
/**
 * Java switch分支结构示例
 * 演示switch语句的各种用法和特性
 */
public class SwitchStructureDemo {
    public static void main(String[] args) {
        
        // ========== 1. 基本switch用法(整数类型) ==========
        System.out.println("========== 1. 基本switch(整数) ==========");
        
        int dayOfWeek = 3;
        String dayName;
        
        switch (dayOfWeek) {
            case 1:
                dayName = "星期一";
                break;
            case 2:
                dayName = "星期二";
                break;
            case 3:
                dayName = "星期三";
                break;
            case 4:
                dayName = "星期四";
                break;
            case 5:
                dayName = "星期五";
                break;
            case 6:
                dayName = "星期六";
                break;
            case 7:
                dayName = "星期日";
                break;
            default:
                dayName = "无效的星期数";
        }
        
        System.out.println("数字 " + dayOfWeek + " 对应:" + dayName);
        
        // ========== 2. switch处理字符 ==========
        System.out.println("\n========== 2. switch处理字符 ==========");
        
        char grade = 'B';
        String description;
        
        switch (grade) {
            case 'A':
                description = "优秀(90-100分)";
                break;
            case 'B':
                description = "良好(80-89分)";
                break;
            case 'C':
                description = "中等(70-79分)";
                break;
            case 'D':
                description = "及格(60-69分)";
                break;
            case 'F':
                description = "不及格(60分以下)";
                break;
            default:
                description = "无效的成绩等级";
        }
        
        System.out.println("等级 " + grade + ":" + description);
        
        // ========== 3. switch处理字符串(Java 7+) ==========
        System.out.println("\n========== 3. switch处理字符串 ==========");
        
        String fruit = "apple";
        String color;
        
        switch (fruit.toLowerCase()) {
            case "apple":
                color = "红色或绿色";
                break;
            case "banana":
                color = "黄色";
                break;
            case "orange":
                color = "橙色";
                break;
            case "grape":
                color = "紫色或绿色";
                break;
            default:
                color = "未知颜色";
        }
        
        System.out.println(fruit + "的颜色是:" + color);
        
        // ========== 4. 多个case标签合并 ==========
        System.out.println("\n========== 4. 多个case合并 ==========");
        
        int month = 2;
        String season;
        
        switch (month) {
            case 12:
            case 1:
            case 2:
                season = "冬季";
                break;
            case 3:
            case 4:
            case 5:
                season = "春季";
                break;
            case 6:
            case 7:
            case 8:
                season = "夏季";
                break;
            case 9:
            case 10:
            case 11:
                season = "秋季";
                break;
            default:
                season = "无效月份";
        }
        
        System.out.println(month + "月属于:" + season);
        
        // ========== 5. switch穿透效果演示 ==========
        System.out.println("\n========== 5. switch穿透效果 ==========");
        
        int number = 2;
        System.out.println("数字 " + number + " 的穿透效果:");
        
        switch (number) {
            case 1:
                System.out.println("执行case 1");
            case 2:
                System.out.println("执行case 2");  // 从这里开始
            case 3:
                System.out.println("执行case 3");  // 穿透到这里
            case 4:
                System.out.println("执行case 4");  // 穿透到这里
                break;                              // 遇到break停止
            default:
                System.out.println("执行default");
        }
        
        // ========== 7. switch表达式(Java 12+预览,Java 14+正式) ==========
        System.out.println("\n========== 7. switch表达式 ==========");
        
        // 使用箭头语法
        int score = 85;
        String level = switch (score / 10) {
            case 10, 9 -> "优秀";
            case 8 -> "良好";
            case 7 -> "中等";
            case 6 -> "及格";
            case 5, 4, 3, 2, 1, 0 -> "不及格";
            default -> "无效分数";
        };
        System.out.println("分数 " + score + " 等级:" + level);
        
        // 使用yield返回值
        String monthName = "JANUARY";
        int days = switch (monthName) {
            case "JANUARY", "MARCH", "MAY", "JULY", "AUGUST", "OCTOBER", "DECEMBER":
                yield 31;
            case "APRIL", "JUNE", "SEPTEMBER", "NOVEMBER":
                yield 30;
            case "FEBRUARY":
                yield 28;
            default:
                yield 0;
        };
        System.out.println(monthName + " 月份有 " + days + " 天");
        
        // ========== 8. 综合应用:简易计算器 ==========
        System.out.println("\n========== 8. 综合应用:简易计算器 ==========");
        
        calculate(10, 5, '+');
        calculate(10, 5, '-');
        calculate(10, 5, '*');
        calculate(10, 5, '/');
        calculate(10, 5, '%');
        calculate(10, 5, '^');  // 无效运算符
        
        // ========== 9. 菜单选择系统 ==========
        System.out.println("\n========== 9. 菜单选择系统 ==========");
        
        int choice = 2;
        menuSystem(choice);
        
        // ========== 10. 注意事项示例 ==========
        System.out.println("\n========== 10. switch注意事项 ==========");
        
        // 错误示例(注释掉,无法编译)
        // double d = 3.14;
        // switch (d) { // 错误:不能使用double
        //     case 3.14:
        //         break;
        // }
        
        // 正确:必须使用整数类型或兼容类型
        long longValue = 100L;
        // switch (longValue) { } // 错误:不能使用long
        
        // 演示case值必须是常量
        final int CONSTANT_VALUE = 10;
        int variableValue = 20;
        
        switch (5) {
            case 5:  // 常量直接量
                System.out.println("使用直接量作为case");
                break;
            case CONSTANT_VALUE:  // 常量变量
                System.out.println("使用常量变量作为case");
                break;
            // case variableValue:  // 错误:不能使用变量
            //     break;
        }
    }
    
    /**
     * 计算器方法
     */
    public static void calculate(int a, int b, char operator) {
        int result = 0;
        boolean valid = true;
        
        switch (operator) {
            case '+':
                result = a + b;
                break;
            case '-':
                result = a - b;
                break;
            case '*':
                result = a * b;
                break;
            case '/':
                if (b != 0) {
                    result = a / b;
                } else {
                    System.out.println("错误:除数不能为0");
                    valid = false;
                }
                break;
            case '%':
                if (b != 0) {
                    result = a % b;
                } else {
                    System.out.println("错误:除数不能为0");
                    valid = false;
                }
                break;
            default:
                System.out.println("错误:无效的运算符 " + operator);
                valid = false;
        }
        
        if (valid) {
            System.out.println(a + " " + operator + " " + b + " = " + result);
        }
    }
    
    /**
     * 菜单系统
     */
    public static void menuSystem(int choice) {
        System.out.println("=== 菜单系统 ===");
        System.out.println("1. 查询余额");
        System.out.println("2. 存款");
        System.out.println("3. 取款");
        System.out.println("4. 转账");
        System.out.println("5. 退出");
        System.out.println("您的选择:" + choice);
        
        switch (choice) {
            case 1:
                System.out.println("执行:查询余额操作");
                // 这里可以调用查询余额的方法
                break;
            case 2:
                System.out.println("执行:存款操作");
                // 这里可以调用存款的方法
                break;
            case 3:
                System.out.println("执行:取款操作");
                // 这里可以调用取款的方法
                break;
            case 4:
                System.out.println("执行:转账操作");
                // 这里可以调用转账的方法
                break;
            case 5:
                System.out.println("感谢使用,再见!");
                System.exit(0);
                break;
            default:
                System.out.println("无效选择,请重新输入");
        }
    }
}

任务实施

打印月份天数

if else

java

public class Main {
    public static void main(String[] args) {
        int month;
        month = Integer.parseInt(args[0]);
        if (month == 2) {
            System.out.println(month + "月有28天");
        } else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
            System.out.println(month + "月有31天");
        }else if (month == 4 || month == 6 || month == 9 || month == 11) {
            System.out.println(month + "月有30天");

        }else {
            System.out.println("无效的月份");
        }
    }
}

switch

java
public class Main {
    public static void main(String[] args) {
        int month;
        month = Integer.parseInt(args[0]);
        
        switch (month) {
            case 2:
                System.out.println(month + "月有28天");
                break;
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                System.out.println(month + "月有31天");
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                System.out.println(month + "月有30天");
                break;
            default:
                System.out.println("无效的月份:" + month);
        }
    }
}

带闰年增强版

java
public class Main {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("请输入月份!");
            return;
        }
        
        int month = Integer.parseInt(args[0]);
        int year = 2024; // 可以传入年份参数
        
        // 判断2月天数(考虑闰年)
        String result = switch (month) {
            case 2 -> {
                boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
                yield month + "月有" + (isLeapYear ? 29 : 28) + "天";
            }
            case 1, 3, 5, 7, 8, 10, 12 -> month + "月有31天";
            case 4, 6, 9, 11 -> month + "月有30天";
            default -> "无效的月份:" + month;
        };
        
        System.out.println(result);
    }
}

判断闰年

java
public class Main {
    public static void main(String[] args) {
        //闰年判断算法
        int year = Integer.parseInt(args[0]);
        int m = year % 100;
        if (m == 0) {
            if ((year % 400 == 0)) {
                System.out.println(year + "年是闰年,2月份有29天");
            } else {
                System.out.println(year + "年不是闰年,2月份有28天");
            }
        } else {
            if ((year % 4 == 0)) {
                System.out.println(year + "年是闰年,2月份有29天");
            } else {
                System.out.println(year + "年不是闰年,2月份有28天");
            }
        }
    }
}

任务 5

1.19 while循环

java

public class While {

    public static void main(String[] args) {
        int i =1,sum=0;
        while(i<=10){
            sum+=i;
            i++;
        }
        System.out.println("1+2+3+4+5+6+7+8+9+10="+sum);
    }
}

1.20 do-while

java
import java.util.Scanner;

public class DoWhile {

    public static void main(String[] args) {
        int i= 1,sum=0;
        Scanner input = new Scanner(System.in);
        int n=input.nextInt();
        do {
            sum+=i;
            i++;
        }while(i<=n);
        System.out.println("1+2+3+...+n="+sum);
    }
}

1.21 For 循环

java
public class For {

    public static void main(String[] args) {
        int i, sum = 0;
        for (i = 0; i <= 10; i++) {
            sum += i;
        }
        System.out.println("1+2+...+10=" + sum);
    }
}

1.22 break语句和continue语句

break
java
public class Break {

    public static void main(String[] args) {
        int i;
        for (i = 1; i <= 10; i++) {
            if (i % 3 == 0) {
                break;
            }
            System.out.println("i=" + i);
        }
        System.out.println("循环中断:i=" + i);
    }
}
continue
java
public class Continue {

    public static void main(String[] args) {
        int i;
        for (i = 1; i <= 10; i++) {
            if (i % 3 == 0) {
                continue;
            }
            System.out.println("i=" + i);
        }
        System.out.println("循环中断:i=" + i);
    }
}

任务实施

while
java

public class While {

    public static void main(String[] args) {
        int num1 = 0;
        int num2 = Integer.parseInt(args[0]);
        int result = Integer.parseInt(args[1]);
        int i = 0;
        while (i < 10) {
            if (i * num2 == result) {
                num1 = i;
                break;
            }
            i++;
        }
        if (i < 10) {
            System.out.println("数字" + num1 + "可以使下面的等式成立:");
            System.out.println("x * " + num2 + " = " + result);
        } else
            System.out.println("没有符合要求的数字");

    }
}

for

java
public class For {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int num1 = 0;
        int num2 = Integer.parseInt(args[0]);
        int result = Integer.parseInt(args[1]);
        int i;
        for (i = 0; i < 10; i++) {
            if (i * num2 == result) {
                num1 = i;
                break;
            }
            if (i < 10) {
                System.out.println("数字" + num1 + "可以使下面的等式成立:");
                System.out.println("x * " + num2 + " = " + result);
            } else
                System.out.println("没有符合要求的数字");

        }
    }
}

Updated At: