Java课堂案例

wen java案例 1

本文目录导读:

Java课堂案例

  1. 基础语法案例
  2. 面向对象案例
  3. 进阶案例
  4. 教学建议

我为您准备了一系列Java课堂案例,从基础到进阶,适合教学演示。

基础语法案例

猜数字游戏(Random + 循环)

import java.util.Scanner;
import java.util.Random;
public class GuessNumber {
    public static void main(String[] args) {
        Random random = new Random();
        int target = random.nextInt(100) + 1;  // 1-100的随机数
        Scanner scanner = new Scanner(System.in);
        System.out.println("=== 猜数字游戏 ===");
        System.out.println("猜一个1-100之间的数字");
        int count = 0;
        int guess;
        do {
            System.out.print("请输入你的猜测: ");
            guess = scanner.nextInt();
            count++;
            if (guess > target) {
                System.out.println("太大了!");
            } else if (guess < target) {
                System.out.println("太小了!");
            } else {
                System.out.println("恭喜你猜对了!用了" + count + "次");
            }
        } while (guess != target);
        scanner.close();
    }
}

学生成绩管理系统(数组+方法)

import java.util.Scanner;
public class ScoreManager {
    static String[] names = new String[50];
    static double[] scores = new double[50];
    static int count = 0;
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choice;
        do {
            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("请选择: ");
            choice = scanner.nextInt();
            switch (choice) {
                case 1: addStudent(scanner); break;
                case 2: displayAll(); break;
                case 3: showStats(); break;
                case 4: searchStudent(scanner); break;
                case 0: System.out.println("再见!"); break;
                default: System.out.println("无效选择");
            }
        } while (choice != 0);
    }
    public static void addStudent(Scanner scanner) {
        System.out.print("输入学生姓名: ");
        scanner.nextLine();
        names[count] = scanner.nextLine();
        System.out.print("输入成绩: ");
        scores[count] = scanner.nextDouble();
        count++;
        System.out.println("添加成功!");
    }
    public static void displayAll() {
        System.out.println("\n姓名\t成绩");
        for (int i = 0; i < count; i++) {
            System.out.println(names[i] + "\t" + scores[i]);
        }
    }
    public static void showStats() {
        if (count == 0) {
            System.out.println("暂无数据");
            return;
        }
        double total = 0;
        double max = scores[0];
        String maxName = names[0];
        for (int i = 0; i < count; i++) {
            total += scores[i];
            if (scores[i] > max) {
                max = scores[i];
                maxName = names[i];
            }
        }
        System.out.println("平均分: " + String.format("%.1f", total/count));
        System.out.println("最高分: " + max + " (由" + maxName + "获得)");
    }
    public static void searchStudent(Scanner scanner) {
        System.out.print("输入要查找的学生姓名: ");
        scanner.nextLine();
        String name = scanner.nextLine();
        for (int i = 0; i < count; i++) {
            if (names[i].equals(name)) {
                System.out.println("找到: " + names[i] + " 成绩: " + scores[i]);
                return;
            }
        }
        System.out.println("未找到该学生");
    }
}

面向对象案例

银行账户管理系统(面向对象)

import java.util.ArrayList;
import java.util.Scanner;
// 账户类
class BankAccount {
    private String accountNumber;
    private String ownerName;
    private double balance;
    public BankAccount(String accountNumber, String ownerName, double initialDeposit) {
        this.accountNumber = accountNumber;
        this.ownerName = ownerName;
        this.balance = initialDeposit;
    }
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("存入 " + amount + " 元,当前余额: " + balance);
        } else {
            System.out.println("存款金额无效!");
        }
    }
    public boolean withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("取出 " + amount + " 元,当前余额: " + balance);
            return true;
        } else {
            System.out.println("取款失败,请检查余额!");
            return false;
        }
    }
    public void displayInfo() {
        System.out.println("=== 账户信息 ===");
        System.out.println("账号: " + accountNumber);
        System.out.println("户主: " + ownerName);
        System.out.println("余额: " + balance);
    }
    // Getter/Setter
    public String getAccountNumber() { return accountNumber; }
    public String getOwnerName() { return ownerName; }
    public double getBalance() { return balance; }
}
public class BankSystem {
    private static ArrayList<BankAccount> accounts = new ArrayList<>();
    private static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        int choice;
        do {
            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("请选择: ");
            choice = scanner.nextInt();
            switch (choice) {
                case 1: createAccount(); break;
                case 2: deposit(); break;
                case 3: withdraw(); break;
                case 4: queryAccount(); break;
                case 5: showAllAccounts(); break;
                case 0: System.out.println("感谢使用!"); break;
                default: System.out.println("无效选择");
            }
        } while (choice != 0);
    }
    private static void createAccount() {
        System.out.print("请输入账号: ");
        String accountNumber = scanner.next();
        System.out.print("请输入户主姓名: ");
        String ownerName = scanner.next();
        System.out.print("请输入初始存款: ");
        double initialDeposit = scanner.nextDouble();
        BankAccount account = new BankAccount(accountNumber, ownerName, initialDeposit);
        accounts.add(account);
        System.out.println("开户成功!");
    }
    private static BankAccount findAccount(String accountNumber) {
        for (BankAccount account : accounts) {
            if (account.getAccountNumber().equals(accountNumber)) {
                return account;
            }
        }
        return null;
    }
    private static void deposit() {
        System.out.print("输入账号: ");
        String accountNumber = scanner.next();
        BankAccount account = findAccount(accountNumber);
        if (account != null) {
            System.out.print("输入存款金额: ");
            double amount = scanner.nextDouble();
            account.deposit(amount);
        } else {
            System.out.println("账户不存在!");
        }
    }
    private static void withdraw() {
        System.out.print("输入账号: ");
        String accountNumber = scanner.next();
        BankAccount account = findAccount(accountNumber);
        if (account != null) {
            System.out.print("输入取款金额: ");
            double amount = scanner.nextDouble();
            account.withdraw(amount);
        } else {
            System.out.println("账户不存在!");
        }
    }
    private static void queryAccount() {
        System.out.print("输入账号: ");
        String accountNumber = scanner.next();
        BankAccount account = findAccount(accountNumber);
        if (account != null) {
            account.displayInfo();
        } else {
            System.out.println("账户不存在!");
        }
    }
    private static void showAllAccounts() {
        if (accounts.isEmpty()) {
            System.out.println("暂无账户");
            return;
        }
        for (BankAccount account : accounts) {
            account.displayInfo();
            System.out.println();
        }
    }
}

动物继承体系

// 抽象类 Animal
abstract class Animal {
    protected String name;
    protected int age;
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    // 抽象方法
    public abstract void makeSound();
    // 普通方法
    public void eat() {
        System.out.println(name + " 正在进食...");
    }
    public void displayInfo() {
        System.out.println("名字: " + name + ", 年龄: " + age);
    }
}
// 子类 Dog
class Dog extends Animal {
    private String breed; // 品种
    public Dog(String name, int age, String breed) {
        super(name, age);
        this.breed = breed;
    }
    @Override
    public void makeSound() {
        System.out.println(name + " 汪汪叫!");
    }
    // 特有方法
    public void wagTail() {
        System.out.println(name + " 摇尾巴!");
    }
}
// 子类 Cat
class Cat extends Animal {
    private boolean indoor; // 家猫还是野猫
    public Cat(String name, int age, boolean indoor) {
        super(name, age);
        this.indoor = indoor;
    }
    @Override
    public void makeSound() {
        System.out.println(name + " 喵喵叫!");
    }
    public void play() {
        System.out.println(name + " 正在玩毛线球!");
    }
}
public class AnimalDemo {
    public static void main(String[] args) {
        System.out.println("=== 多态演示 ===");
        // 创建对象
        Dog dog = new Dog("旺财", 3, "金毛");
        Cat cat = new Cat("咪咪", 2, true);
        // 多态引用
        Animal[] animals = {dog, cat};
        for (Animal animal : animals) {
            animal.displayInfo();
            animal.makeSound();  // 动态绑定
            animal.eat();
            System.out.println();
        }
        // 调用特有方法
        dog.wagTail();
        cat.play();
        // 类型检查
        if (dog instanceof Animal) {
            System.out.println("\n旺财是Animal的子类");
        }
        if (cat instanceof Object) {
            System.out.println("咪咪是Object的子类");
        }
    }
}

进阶案例

简易计算器(GUI界面)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
    private JTextField display;
    private double firstNum = 0;
    private String operator = "";
    private boolean startNewNumber = true;
    public Calculator() {
        setTitle("简易计算器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());
        // 显示区域
        display = new JTextField();
        display.setFont(new Font("Arial", Font.BOLD, 24));
        display.setHorizontalAlignment(JTextField.RIGHT);
        display.setEditable(false);
        add(display, BorderLayout.NORTH);
        // 按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(4, 4, 5, 5));
        String[] buttons = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "=", "+"
        };
        for (String text : buttons) {
            JButton button = new JButton(text);
            button.setFont(new Font("Arial", Font.BOLD, 18));
            button.addActionListener(this);
            if ("/+-*=".contains(text)) {
                button.setBackground(Color.LIGHT_GRAY);
            }
            buttonPanel.add(button);
        }
        add(buttonPanel, BorderLayout.CENTER);
        // 设置窗口大小和位置
        setSize(400, 400);
        setLocationRelativeTo(null);
        setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if ("0123456789.".contains(command)) {
            if (startNewNumber) {
                display.setText("");
                startNewNumber = false;
            }
            display.setText(display.getText() + command);
        } else if (command.equals("=")) {
            calculate();
            operator = "";
            startNewNumber = true;
        } else { // 运算符
            if (!operator.isEmpty() && !startNewNumber) {
                calculate();
            }
            firstNum = Double.parseDouble(display.getText());
            operator = command;
            startNewNumber = true;
        }
    }
    private void calculate() {
        try {
            double secondNum = Double.parseDouble(display.getText());
            double result = 0;
            switch (operator) {
                case "+": result = firstNum + secondNum; break;
                case "-": result = firstNum - secondNum; break;
                case "*": result = firstNum * secondNum; break;
                case "/": 
                    if (secondNum == 0) {
                        display.setText("除数不能为0");
                        return;
                    }
                    result = firstNum / secondNum; break;
                default: return;
            }
            display.setText(String.valueOf(result));
        } catch (NumberFormatException ex) {
            display.setText("错误");
        }
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new Calculator());
    }
}

文件操作 - 通讯录

import java.io.*;
import java.util.*;
class Contact implements Serializable {
    private String name;
    private String phone;
    private String email;
    public Contact(String name, String phone, String email) {
        this.name = name;
        this.phone = phone;
        this.email = email;
    }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getPhone() { return phone; }
    public void setPhone(String phone) { this.phone = phone; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    @Override
    public String toString() {
        return String.format("姓名: %s 电话: %s 邮箱: %s", name, phone, email);
    }
}
public class ContactBook {
    private static List<Contact> contacts = new ArrayList<>();
    private static final String FILE_NAME = "contacts.dat";
    private static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        loadContacts();
        int choice;
        do {
            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("请选择: ");
            choice = scanner.nextInt();
            scanner.nextLine();  // 清空缓冲区
            switch (choice) {
                case 1: addContact(); break;
                case 2: deleteContact(); break;
                case 3: updateContact(); break;
                case 4: searchContact(); break;
                case 5: showAllContacts(); break;
                case 6: saveContacts(); break;
                case 0: 
                    saveContacts();
                    System.out.println("数据已保存,再见!"); 
                    break;
                default: System.out.println("无效选择");
            }
        } while (choice != 0);
    }
    private static void addContact() {
        System.out.print("输入姓名: ");
        String name = scanner.nextLine();
        System.out.print("输入电话: ");
        String phone = scanner.nextLine();
        System.out.print("输入邮箱: ");
        String email = scanner.nextLine();
        contacts.add(new Contact(name, phone, email));
        System.out.println("联系人添加成功!");
    }
    private static void deleteContact() {
        System.out.print("输入要删除的联系人姓名: ");
        String name = scanner.nextLine();
        boolean removed = contacts.removeIf(c -> c.getName().equals(name));
        if (removed) {
            System.out.println("删除成功!");
        } else {
            System.out.println("未找到该联系人");
        }
    }
    private static void updateContact() {
        System.out.print("输入要修改的联系人姓名: ");
        String name = scanner.nextLine();
        for (Contact contact : contacts) {
            if (contact.getName().equals(name)) {
                System.out.print("输入新的电话 (留空保持不变): ");
                String newPhone = scanner.nextLine();
                if (!newPhone.isEmpty()) {
                    contact.setPhone(newPhone);
                }
                System.out.print("输入新的邮箱 (留空保持不变): ");
                String newEmail = scanner.nextLine();
                if (!newEmail.isEmpty()) {
                    contact.setEmail(newEmail);
                }
                System.out.println("修改成功!");
                return;
            }
        }
        System.out.println("未找到该联系人");
    }
    private static void searchContact() {
        System.out.print("输入要查找的姓名或电话: ");
        String keyword = scanner.nextLine();
        boolean found = false;
        for (Contact contact : contacts) {
            if (contact.getName().contains(keyword) || 
                contact.getPhone().contains(keyword)) {
                System.out.println(contact);
                found = true;
            }
        }
        if (!found) {
            System.out.println("未找到相关联系人");
        }
    }
    private static void showAllContacts() {
        if (contacts.isEmpty()) {
            System.out.println("通讯录为空");
            return;
        }
        System.out.println("\n=== 所有联系人 ===");
        for (int i = 0; i < contacts.size(); i++) {
            System.out.println((i+1) + ". " + contacts.get(i));
        }
    }
    private static void saveContacts() {
        try (ObjectOutputStream oos = 
                new ObjectOutputStream(new FileOutputStream(FILE_NAME))) {
            oos.writeObject(contacts);
            System.out.println("数据保存成功!");
        } catch (IOException e) {
            System.out.println("保存失败: " + e.getMessage());
        }
    }
    @SuppressWarnings("unchecked")
    private static void loadContacts() {
        File file = new File(FILE_NAME);
        if (!file.exists()) {
            System.out.println("首次运行,创建新通讯录");
            return;
        }
        try (ObjectInputStream ois = 
                new ObjectInputStream(new FileInputStream(FILE_NAME))) {
            contacts = (List<Contact>) ois.readObject();
            System.out.println("加载了 " + contacts.size() + " 个联系人");
        } catch (Exception e) {
            System.out.println("加载失败: " + e.getMessage());
        }
    }
}

教学建议

使用说明

  1. 循序渐进:按照基础 → 面向对象 → 进阶的顺序教学
  2. 实战结合:每个案例都包含实际应用场景
  3. 交互设计:所有案例都包含用户交互
  4. 代码注释:详细的注释便于理解

教学要点提示

  • 每次只讲解一个新概念
  • 让学生先运行查看效果,再讲解原理
  • 适当提问引导思考
  • 鼓励学生修改变量值观察结果变化
  • 最后可以让学生扩展功能作为作业

这些案例覆盖了Java的核心知识点,适合课堂教学使用,每个案例都可以单独运行,也可以根据需要修改扩展。

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