Java作业案例

wen java案例 2

本文目录导读:

Java作业案例

  1. 案例一:学生成绩管理系统(面向对象基础)
  2. 案例二:字符串处理工具(字符串与数组练习)
  3. 案例三:简单银行账户系统(继承与多态)
  4. 案例四:经典算法集合(算法与逻辑练习)
  5. 案例五:万年历程序(日期处理练习)
  6. 使用建议

我为您准备了一个综合性的Java作业案例,包含多个典型练习,从基础到进阶都有覆盖,每个案例都包含完整代码和运行结果。

学生成绩管理系统(面向对象基础)

import java.util.ArrayList;
import java.util.Scanner;
public class StudentManager {
    // 学生类
    static class Student {
        private String id;
        private String name;
        private double score;
        public Student(String id, String name, double score) {
            this.id = id;
            this.name = name;
            this.score = score;
        }
        public String getId() { return id; }
        public String getName() { return name; }
        public double getScore() { return score; }
        public void setScore(double score) { this.score = score; }
        @Override
        public String toString() {
            return String.format("学号: %s, 姓名: %s, 成绩: %.1f", id, name, score);
        }
    }
    private ArrayList<Student> students = new ArrayList<>();
    private Scanner scanner = new Scanner(System.in);
    public void run() {
        while (true) {
            System.out.println("\n===== 学生成绩管理系统 =====");
            System.out.println("1. 添加学生");
            System.out.println("2. 删除学生");
            System.out.println("3. 修改学生成绩");
            System.out.println("4. 查询学生");
            System.out.println("5. 显示所有学生");
            System.out.println("6. 统计成绩信息");
            System.out.println("0. 退出系统");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符
            switch (choice) {
                case 1: addStudent(); break;
                case 2: deleteStudent(); break;
                case 3: updateScore(); break;
                case 4: searchStudent(); break;
                case 5: displayAll(); break;
                case 6: showStatistics(); break;
                case 0: 
                    System.out.println("感谢使用,再见!");
                    return;
                default:
                    System.out.println("无效选择,请重新输入!");
            }
        }
    }
    private void addStudent() {
        System.out.print("请输入学号: ");
        String id = scanner.nextLine();
        // 检查学号是否已存在
        for (Student s : students) {
            if (s.getId().equals(id)) {
                System.out.println("该学号已存在!");
                return;
            }
        }
        System.out.print("请输入姓名: ");
        String name = scanner.nextLine();
        System.out.print("请输入成绩: ");
        double score = scanner.nextDouble();
        students.add(new Student(id, name, score));
        System.out.println("学生添加成功!");
    }
    private void deleteStudent() {
        System.out.print("请输入要删除的学号: ");
        String id = scanner.nextLine();
        for (int i = 0; i < students.size(); i++) {
            if (students.get(i).getId().equals(id)) {
                students.remove(i);
                System.out.println("删除成功!");
                return;
            }
        }
        System.out.println("未找到该学号的学生!");
    }
    private void updateScore() {
        System.out.print("请输入要修改的学号: ");
        String id = scanner.nextLine();
        for (Student s : students) {
            if (s.getId().equals(id)) {
                System.out.print("请输入新的成绩: ");
                double newScore = scanner.nextDouble();
                s.setScore(newScore);
                System.out.println("成绩修改成功!");
                return;
            }
        }
        System.out.println("未找到该学号的学生!");
    }
    private void searchStudent() {
        System.out.print("请输入要查询的学号或姓名: ");
        String keyword = scanner.nextLine();
        boolean found = false;
        for (Student s : students) {
            if (s.getId().equals(keyword) || s.getName().equals(keyword)) {
                System.out.println(s);
                found = true;
            }
        }
        if (!found) {
            System.out.println("未找到匹配的学生!");
        }
    }
    private void displayAll() {
        if (students.isEmpty()) {
            System.out.println("暂无学生数据!");
            return;
        }
        System.out.println("\n所有学生信息:");
        System.out.println("----------------");
        for (Student s : students) {
            System.out.println(s);
        }
    }
    private void showStatistics() {
        if (students.isEmpty()) {
            System.out.println("暂无数据可统计!");
            return;
        }
        double max = Double.MIN_VALUE;
        double min = Double.MAX_VALUE;
        double sum = 0;
        for (Student s : students) {
            max = Math.max(max, s.getScore());
            min = Math.min(min, s.getScore());
            sum += s.getScore();
        }
        double avg = sum / students.size();
        System.out.printf("学生人数: %d\n", students.size());
        System.out.printf("最高分: %.1f\n", max);
        System.out.printf("最低分: %.1f\n", min);
        System.out.printf("平均分: %.1f\n", avg);
        System.out.printf("及格率: %.1f%%\n", 
            (double)students.stream().filter(s -> s.getScore() >= 60).count() / students.size() * 100);
    }
    public static void main(String[] args) {
        new StudentManager().run();
    }
}

字符串处理工具(字符串与数组练习)

public class StringTools {
    // 统计字符出现次数
    public static int countChar(String str, char c) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == c) count++;
        }
        return count;
    }
    // 反转字符串
    public static String reverse(String str) {
        return new StringBuilder(str).reverse().toString();
    }
    // 判断是否为回文
    public static boolean isPalindrome(String str) {
        str = str.toLowerCase().replaceAll("[^a-z0-9]", "");
        int left = 0, right = str.length() - 1;
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
    // 统计单词数量
    public static int countWords(String str) {
        if (str == null || str.trim().isEmpty()) return 0;
        return str.trim().split("\\s+").length;
    }
    // 提取所有数字
    public static String extractNumbers(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {
                sb.append(str.charAt(i));
            }
        }
        return sb.toString();
    }
    // 首字母大写
    public static String capitalizeWords(String str) {
        String[] words = str.toLowerCase().split("\\s+");
        StringBuilder result = new StringBuilder();
        for (String word : words) {
            if (!word.isEmpty()) {
                result.append(Character.toUpperCase(word.charAt(0)))
                      .append(word.substring(1))
                      .append(" ");
            }
        }
        return result.toString().trim();
    }
    public static void main(String[] args) {
        String testStr = "Hello World 123 Java Programming";
        System.out.println("原字符串: " + testStr);
        System.out.println("字符 'o' 出现次数: " + countChar(testStr, 'o'));
        System.out.println("反转字符串: " + reverse(testStr));
        System.out.println("是否为回文: " + isPalindrome("A man, a plan, a canal: Panama"));
        System.out.println("单词数量: " + countWords(testStr));
        System.out.println("提取数字: " + extractNumbers(testStr));
        System.out.println("单词首字母大写: " + capitalizeWords("hello world java"));
    }
}

简单银行账户系统(继承与多态)

import java.util.ArrayList;
import java.util.Scanner;
public class BankSystem {
    // 账户抽象类
    abstract static class Account {
        protected String accountNo;
        protected String holderName;
        protected double balance;
        public Account(String accountNo, String holderName, double initialBalance) {
            this.accountNo = accountNo;
            this.holderName = holderName;
            this.balance = initialBalance;
        }
        // 抽象方法
        public abstract double calculateInterest();
        public abstract void displayAccountType();
        // 公共方法
        public void deposit(double amount) {
            if (amount > 0) {
                balance += amount;
                System.out.println("存款成功,当前余额: " + balance);
            } else {
                System.out.println("存款金额必须大于0!");
            }
        }
        public void withdraw(double amount) {
            if (amount > 0 && amount <= balance) {
                balance -= amount;
                System.out.println("取款成功,当前余额: " + balance);
            } else {
                System.out.println("取款失败,余额不足或金额无效!");
            }
        }
        public void displayInfo() {
            System.out.println("账户类型: ");
            displayAccountType();
            System.out.println("账号: " + accountNo);
            System.out.println("户主: " + holderName);
            System.out.println("余额: " + balance + " 元");
            System.out.println("年利息: " + calculateInterest() + " 元");
        }
    }
    // 储蓄账户
    static class SavingsAccount extends Account {
        private double interestRate = 0.03; // 3% 年利率
        public SavingsAccount(String accountNo, String holderName, double initialBalance) {
            super(accountNo, holderName, initialBalance);
        }
        @Override
        public double calculateInterest() {
            return balance * interestRate;
        }
        @Override
        public void displayAccountType() {
            System.out.println("储蓄账户");
        }
    }
    // 支票账户
    static class CheckingAccount extends Account {
        private double transactionFee = 2.0; // 每次交易手续费
        public CheckingAccount(String accountNo, String holderName, double initialBalance) {
            super(accountNo, holderName, initialBalance);
        }
        @Override
        public void withdraw(double amount) {
            if (amount + transactionFee <= balance) {
                balance -= (amount + transactionFee);
                System.out.println("取款成功(含手续费" + transactionFee + "元),当前余额: " + balance);
            } else {
                System.out.println("取款失败,余额不足!");
            }
        }
        @Override
        public double calculateInterest() {
            return 0; // 支票账户无利息
        }
        @Override
        public void displayAccountType() {
            System.out.println("支票账户");
        }
    }
    public static void main(String[] args) {
        ArrayList<Account> accounts = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        // 创建一些测试账户
        accounts.add(new SavingsAccount("SA001", "张三", 10000));
        accounts.add(new CheckingAccount("CA001", "李四", 5000));
        while (true) {
            System.out.println("\n===== 银行账户系统 =====");
            System.out.println("1. 显示所有账户");
            System.out.println("2. 存款");
            System.out.println("3. 取款");
            System.out.println("4. 创建新账户");
            System.out.println("0. 退出");
            System.out.print("请选择: ");
            int choice = scanner.nextInt();
            scanner.nextLine();
            switch (choice) {
                case 1:
                    for (Account acc : accounts) {
                        acc.displayInfo();
                        System.out.println("-------------------");
                    }
                    break;
                case 2:
                    System.out.print("请输入账号: ");
                    String accNo = scanner.nextLine();
                    Account account = findAccount(accounts, accNo);
                    if (account != null) {
                        System.out.print("请输入存款金额: ");
                        double amount = scanner.nextDouble();
                        account.deposit(amount);
                    } else {
                        System.out.println("账户不存在!");
                    }
                    break;
                case 3:
                    System.out.print("请输入账号: ");
                    accNo = scanner.nextLine();
                    account = findAccount(accounts, accNo);
                    if (account != null) {
                        System.out.print("请输入取款金额: ");
                        double amount = scanner.nextDouble();
                        account.withdraw(amount);
                    } else {
                        System.out.println("账户不存在!");
                    }
                    break;
                case 4:
                    System.out.print("请输入账户类型(1-储蓄,2-支票): ");
                    int type = scanner.nextInt();
                    scanner.nextLine();
                    System.out.print("请输入账号: ");
                    String newAccNo = scanner.nextLine();
                    System.out.print("请输入持有人姓名: ");
                    String name = scanner.nextLine();
                    System.out.print("请输入初始存款: ");
                    double initDeposit = scanner.nextDouble();
                    Account newAccount = (type == 1) ? 
                        new SavingsAccount(newAccNo, name, initDeposit) :
                        new CheckingAccount(newAccNo, name, initDeposit);
                    accounts.add(newAccount);
                    System.out.println("账户创建成功!");
                    break;
                case 0:
                    System.out.println("感谢使用银行系统!");
                    scanner.close();
                    return;
                default:
                    System.out.println("无效选择!");
            }
        }
    }
    private static Account findAccount(ArrayList<Account> accounts, String accountNo) {
        for (Account acc : accounts) {
            if (acc.accountNo.equals(accountNo)) {
                return acc;
            }
        }
        return null;
    }
}

经典算法集合(算法与逻辑练习)

import java.util.Arrays;
import java.util.Random;
public class AlgorithmExercises {
    // 冒泡排序
    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            boolean swapped = false;
            for (int j = 0; j < n - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }
            if (!swapped) break; // 优化:如果没有交换说明已排序
        }
    }
    // 二分查找
    public static int binarySearch(int[] arr, int target) {
        int left = 0, right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) return mid;
            if (arr[mid] < target) left = mid + 1;
            else right = mid - 1;
        }
        return -1; // 未找到
    }
    // 计算斐波那契数列(递归)
    public static long fibonacci(int n) {
        if (n <= 1) return n;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
    // 计算斐波那契数列(迭代,更高效)
    public static long fibonacciIterative(int n) {
        if (n <= 1) return n;
        long prev = 0, curr = 1;
        for (int i = 2; i <= n; i++) {
            long temp = curr;
            curr = prev + curr;
            prev = temp;
        }
        return curr;
    }
    // 最大公约数(欧几里得算法)
    public static int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return Math.abs(a);
    }
    // 判断素数
    public static boolean isPrime(int n) {
        if (n < 2) return false;
        if (n == 2 || n == 3) return true;
        if (n % 2 == 0 || n % 3 == 0) return false;
        for (int i = 5; i * i <= n; i += 6) {
            if (n % i == 0 || n % (i + 2) == 0) return false;
        }
        return true;
    }
    // 数组反转
    public static void reverseArray(int[] arr) {
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }
    public static void main(String[] args) {
        // 测试排序
        int[] arr = {64, 34, 25, 12, 22, 11, 90};
        System.out.println("排序前: " + Arrays.toString(arr));
        bubbleSort(arr);
        System.out.println("排序后: " + Arrays.toString(arr));
        // 测试二分查找
        int index = binarySearch(arr, 22);
        System.out.println("查找22的位置: " + index);
        // 测试斐波那契
        System.out.println("斐波那契数列前10项:");
        for (int i = 0; i < 10; i++) {
            System.out.print(fibonacci(i) + " ");
        }
        System.out.println();
        // 测试最大公约数
        System.out.println("gcd(56, 98) = " + gcd(56, 98));
        // 测试素数
        System.out.println("1-50之间的素数:");
        for (int i = 1; i <= 50; i++) {
            if (isPrime(i)) {
                System.out.print(i + " ");
            }
        }
        System.out.println();
        // 测试数组反转
        int[] arr2 = {1, 2, 3, 4, 5};
        reverseArray(arr2);
        System.out.println("反转数组: " + Arrays.toString(arr2));
    }
}

万年历程序(日期处理练习)

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class CalendarApplication {
    // 打印一个月日历
    public static void printMonth(int year, int month) {
        YearMonth yearMonth = YearMonth.of(year, month);
        int days = yearMonth.lengthOfMonth();
        LocalDate firstDay = yearMonth.atDay(1);
        // 第一天是星期几(1=周一, 7=周日)
        int dayOfWeek = firstDay.getDayOfWeek().getValue();
        System.out.println("\n      " + year + "年 " + month + "月");
        System.out.println(" 一  二  三  四  五  六  日");
        System.out.println("===========================");
        // 打印前面的空格
        for (int i = 1; i < dayOfWeek; i++) {
            System.out.print("    ");
        }
        // 打印日期
        for (int day = 1; day <= days; day++) {
            System.out.printf("%3d ", day);
            if ((day + dayOfWeek - 1) % 7 == 0) {
                System.out.println();
            }
        }
        System.out.println();
    }
    // 判断是否闰年
    public static boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
    // 计算两个日期之间的天数
    public static long daysBetween(LocalDate date1, LocalDate date2) {
        // 确保date1是较早的日期
        if (date1.isAfter(date2)) {
            LocalDate temp = date1;
            date1 = date2;
            date2 = temp;
        }
        return date1.until(date2).getDays();
    }
    // 显示当前日期信息
    public static void showCurrentDate() {
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE");
        System.out.println("当前日期: " + today.format(formatter));
        System.out.println("今天是今年的第 " + today.getDayOfYear() + " 天");
        System.out.println("今年还剩 " + (today.lengthOfYear() - today.getDayOfYear()) + " 天");
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        LocalDate today = LocalDate.now();
        while (true) {
            System.out.println("\n===== 万年历程序 =====");
            System.out.println("1. 显示某月日历");
            System.out.println("2. 显示今年全年日历");
            System.out.println("3. 判断闰年");
            System.out.println("4. 计算日期差");
            System.out.println("5. 显示当前日期信息");
            System.out.println("0. 退出");
            System.out.print("请选择: ");
            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    System.out.print("请输入年份: ");
                    int year = scanner.nextInt();
                    System.out.print("请输入月份(1-12): ");
                    int month = scanner.nextInt();
                    printMonth(year, month);
                    break;
                case 2:
                    System.out.print("请输入年份: ");
                    year = scanner.nextInt();
                    for (int m = 1; m <= 12; m++) {
                        printMonth(year, m);
                    }
                    break;
                case 3:
                    System.out.print("请输入年份: ");
                    year = scanner.nextInt();
                    System.out.println(year + "年" + (isLeapYear(year) ? "是" : "不是") + "闰年");
                    break;
                case 4:
                    System.out.print("请输入第一个日期 (YYYY-MM-DD): ");
                    String dateStr1 = scanner.next();
                    System.out.print("请输入第二个日期 (YYYY-MM-DD): ");
                    String dateStr2 = scanner.next();
                    LocalDate date1 = LocalDate.parse(dateStr1);
                    LocalDate date2 = LocalDate.parse(dateStr2);
                    long days = daysBetween(date1, date2);
                    System.out.println("两个日期相差 " + days + " 天");
                    break;
                case 5:
                    showCurrentDate();
                    break;
                case 0:
                    System.out.println("感谢使用万年历程序!");
                    scanner.close();
                    return;
                default:
                    System.out.println("无效选择!");
            }
        }
    }
}

使用建议

  1. 选做题:根据您当前的Java水平选择合适的案例

    • 初学者:从案例二(字符串工具)开始
    • 中级水平:尝试案例一(学生管理系统)
    • 进阶水平:挑战案例三(银行系统)
  2. 扩展提升

    • 为案例一添加文件保存/读取功能
    • 为案例三添加数据库连接
    • 为案例四添加更复杂的排序算法
  3. 注意要点

    • 代码规范:变量命名、注释规范
    • 异常处理:添加 try-catch 处理用户输入错误
    • 代码复用:思考如何优化现有代码

如果需要任何案例的详细解释或修改,请告诉我!

抱歉,评论功能暂时关闭!