本文目录导读:

我来为您提供几个典型的Java需求案例,从基础到进阶,适合不同学习阶段。
基础案例:学生成绩管理系统
需求描述
实现一个简单的学生成绩管理系统,支持学生信息的增删改查。
实现代码
import java.util.*;
public class StudentGradeManager {
private Map<String, Student> students = new HashMap<>();
// 学生类
static class Student {
String id;
String name;
double score;
public Student(String id, String name, double score) {
this.id = id;
this.name = name;
this.score = score;
}
@Override
public String toString() {
return String.format("学号: %s, 姓名: %s, 成绩: %.1f", id, name, score);
}
}
// 添加学生
public void addStudent(String id, String name, double score) {
students.put(id, new Student(id, name, score));
System.out.println("添加成功!");
}
// 删除学生
public void removeStudent(String id) {
if (students.remove(id) != null) {
System.out.println("删除成功!");
} else {
System.out.println("未找到该学生!");
}
}
// 查找学生
public void findStudent(String id) {
Student student = students.get(id);
if (student != null) {
System.out.println(student);
} else {
System.out.println("未找到该学生!");
}
}
// 显示所有学生
public void displayAll() {
if (students.isEmpty()) {
System.out.println("暂无学生信息");
return;
}
students.values().stream()
.sorted((a,b) -> Double.compare(b.score, a.score))
.forEach(System.out::println);
}
public static void main(String[] args) {
StudentGradeManager manager = new StudentGradeManager();
Scanner scanner = new Scanner(System.in);
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.print("请选择操作: ");
int choice = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
switch (choice) {
case 1:
System.out.print("请输入学号: ");
String id = scanner.nextLine();
System.out.print("请输入姓名: ");
String name = scanner.nextLine();
System.out.print("请输入成绩: ");
double score = scanner.nextDouble();
manager.addStudent(id, name, score);
break;
case 2:
System.out.print("请输入要删除的学号: ");
String delId = scanner.nextLine();
manager.removeStudent(delId);
break;
case 3:
System.out.print("请输入要查找的学号: ");
String findId = scanner.nextLine();
manager.findStudent(findId);
break;
case 4:
manager.displayAll();
break;
case 5:
System.out.println("感谢使用!");
return;
default:
System.out.println("无效选择!");
}
}
}
}
进阶案例:简易银行账户系统
需求描述
实现银行账户的存取款、转账、交易记录查询功能。
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
// 交易记录类
class Transaction {
private String type;
private double amount;
private double balance;
private LocalDateTime time;
public Transaction(String type, double amount, double balance) {
this.type = type;
this.amount = amount;
this.balance = balance;
this.time = LocalDateTime.now();
}
@Override
public String toString() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return String.format("[%s] %s: %.2f, 余额: %.2f",
time.format(formatter), type, amount, balance);
}
}
// 银行账户类
class BankAccount {
private String accountNumber;
private String holderName;
private double balance;
private List<Transaction> transactions;
private static final double MIN_BALANCE = 100.0;
public BankAccount(String accountNumber, String holderName, double initialBalance) {
this.accountNumber = accountNumber;
this.holderName = holderName;
this.balance = initialBalance;
this.transactions = new ArrayList<>();
addTransaction("开户", initialBalance);
}
public synchronized boolean deposit(double amount) {
if (amount <= 0) {
System.out.println("存款金额必须为正数!");
return false;
}
balance += amount;
addTransaction("存款", amount);
System.out.printf("存款成功!当前余额: %.2f\n", balance);
return true;
}
public synchronized boolean withdraw(double amount) {
if (amount <= 0) {
System.out.println("取款金额必须为正数!");
return false;
}
if (balance - amount < MIN_BALANCE) {
System.out.println("余额不足!需保留最低余额100元");
return false;
}
balance -= amount;
addTransaction("取款", amount);
System.out.printf("取款成功!当前余额: %.2f\n", balance);
return true;
}
public synchronized boolean transfer(BankAccount target, double amount) {
if (this.withdraw(amount)) {
target.deposit(amount);
addTransaction("转账支出", amount);
target.addTransaction("转账收入", amount);
return true;
}
return false;
}
private void addTransaction(String type, double amount) {
transactions.add(new Transaction(type, amount, balance));
}
public void showTransactionHistory() {
System.out.println("\n交易记录:");
transactions.forEach(System.out::println);
}
public String getAccountInfo() {
return String.format("账号: %s\n户主: %s\n余额: %.2f",
accountNumber, holderName, balance);
}
// Getters
public String getAccountNumber() { return accountNumber; }
public double getBalance() { return balance; }
}
// 银行系统
public class BankingSystem {
private Map<String, BankAccount> accounts = new HashMap<>();
private Scanner scanner = new Scanner(System.in);
public void createAccount() {
System.out.print("请输入账号: ");
String accountNumber = scanner.nextLine();
System.out.print("请输入户主姓名: ");
String holderName = scanner.nextLine();
System.out.print("请输入初始存款: ");
double initialBalance = scanner.nextDouble();
scanner.nextLine();
accounts.put(accountNumber, new BankAccount(accountNumber, holderName, initialBalance));
System.out.println("开户成功!");
}
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("7. 退出");
System.out.print("请选择: ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
createAccount();
break;
case 2:
// 存款操作
break;
case 7:
System.out.println("感谢使用!");
return;
default:
System.out.println("无效选择!");
}
}
}
public static void main(String[] args) {
new BankingSystem().run();
}
}
实用工具案例:文件批处理工具
需求描述
实现批量重命名文件和目录统计功能。
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class FileBatchProcessor {
// 批量重命名文件
public static void renameFiles(String directory, String prefix, String extension) {
File dir = new File(directory);
File[] files = dir.listFiles((d, name) -> name.endsWith(extension));
if (files == null || files.length == 0) {
System.out.println("未找到匹配的文件");
return;
}
int count = 1;
for (File file : files) {
String newName = String.format("%s_%d%s", prefix, count++, extension);
File newFile = new File(dir, newName);
if (file.renameTo(newFile)) {
System.out.printf("重命名: %s -> %s\n", file.getName(), newName);
} else {
System.out.printf("重命名失败: %s\n", file.getName());
}
}
}
// 统计目录信息
public static void directoryStats(String path) throws IOException {
Path dirPath = Paths.get(path);
if (!Files.exists(dirPath) || !Files.isDirectory(dirPath)) {
System.out.println("无效的目录路径");
return;
}
Map<String, Long> extensionCount = new HashMap<>();
long totalSize = 0;
int fileCount = 0;
int dirCount = 0;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dirPath)) {
for (Path entry : stream) {
if (Files.isDirectory(entry)) {
dirCount++;
} else {
fileCount++;
String fileName = entry.getFileName().toString();
String ext = fileName.contains(".") ?
fileName.substring(fileName.lastIndexOf(".")) : "无扩展名";
extensionCount.merge(ext, 1L, Long::sum);
totalSize += Files.size(entry);
}
}
}
System.out.println("\n=== 目录统计 ===");
System.out.printf("目录:%s\n", path);
System.out.printf("文件总数:%d\n", fileCount);
System.out.printf("子目录数:%d\n", dirCount);
System.out.printf("总大小:%.2f MB\n", totalSize / (1024.0 * 1024.0));
System.out.println("\n文件类型统计:");
extensionCount.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.forEach(e -> System.out.printf(" %s: %d个\n", e.getKey(), e.getValue()));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\n=== 文件批处理工具 ===");
System.out.println("1. 批量重命名文件");
System.out.println("2. 目录统计");
System.out.println("3. 退出");
System.out.print("请选择: ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
System.out.print("请输入目录路径: ");
String dir = scanner.nextLine();
System.out.print("请输入文件前缀: ");
String prefix = scanner.nextLine();
System.out.print("请输入文件扩展名(如.txt): ");
String ext = scanner.nextLine();
renameFiles(dir, prefix, ext);
break;
case 2:
System.out.print("请输入目录路径: ");
String path = scanner.nextLine();
try {
directoryStats(path);
} catch (IOException e) {
System.out.println("处理出错: " + e.getMessage());
}
break;
case 3:
System.out.println("感谢使用!");
return;
default:
System.out.println("无效选择!");
}
}
}
}
设计模式案例:简易订单系统
需求描述
使用工厂模式和观察者模式实现订单处理系统。
import java.util.*;
// 1. 工厂模式 - 创建不同类型的订单
interface Order {
void process();
double calculateTotal();
}
class PhysicalOrder implements Order {
private double amount;
private double shippingCost;
public PhysicalOrder(double amount, double shippingCost) {
this.amount = amount;
this.shippingCost = shippingCost;
}
@Override
public void process() {
System.out.println("处理实物订单:准备发货");
}
@Override
public double calculateTotal() {
return amount + shippingCost;
}
}
class DigitalOrder implements Order {
private double amount;
private String downloadLink;
public DigitalOrder(double amount, String downloadLink) {
this.amount = amount;
this.downloadLink = downloadLink;
}
@Override
public void process() {
System.out.println("处理数字订单:发送下载链接 " + downloadLink);
}
@Override
public double calculateTotal() {
return amount; // 数字产品免运费
}
}
// 2. 观察者模式 - 订单通知
interface OrderObserver {
void onOrderCreated(Order order);
void onOrderProcessed(Order order);
}
class EmailNotifier implements OrderObserver {
@Override
public void onOrderCreated(Order order) {
System.out.println("[邮件通知] 订单已创建,金额:" + order.calculateTotal());
}
@Override
public void onOrderProcessed(Order order) {
System.out.println("[邮件通知] 订单已处理完成");
}
}
class SMSNotifier implements OrderObserver {
@Override
public void onOrderCreated(Order order) {
System.out.println("[短信通知] 您有新订单!");
}
@Override
public void onOrderProcessed(Order order) {
System.out.println("[短信通知] 订单处理完成,请查收");
}
}
// 3. 订单管理器
class OrderManager {
private List<Order> orders = new ArrayList<>();
private List<OrderObserver> observers = new ArrayList<>();
public void addObserver(OrderObserver observer) {
observers.add(observer);
}
public void createOrder(Order order) {
orders.add(order);
observers.forEach(obs -> obs.onOrderCreated(order));
}
public void processAllOrders() {
for (Order order : orders) {
order.process();
observers.forEach(obs -> obs.onOrderProcessed(order));
}
}
public double getTotalRevenue() {
return orders.stream().mapToDouble(Order::calculateTotal).sum();
}
}
// 订单工厂
class OrderFactory {
public static Order createOrder(String type, double amount, String extra) {
switch (type.toLowerCase()) {
case "physical":
double shippingCost = Double.parseDouble(extra);
return new PhysicalOrder(amount, shippingCost);
case "digital":
return new DigitalOrder(amount, extra);
default:
throw new IllegalArgumentException("未知订单类型: " + type);
}
}
}
// 主测试类
public class OrderSystem {
public static void main(String[] args) {
OrderManager manager = new OrderManager();
// 注册观察者
manager.addObserver(new EmailNotifier());
manager.addObserver(new SMSNotifier());
// 创建订单
Order physicalOrder = OrderFactory.createOrder("physical", 299.99, "25.00");
Order digitalOrder = OrderFactory.createOrder("digital", 99.99, "https://download.example.com/product");
manager.createOrder(physicalOrder);
manager.createOrder(digitalOrder);
System.out.println("\n=== 处理所有订单 ===");
manager.processAllOrders();
System.out.printf("\n总收入: %.2f\n", manager.getTotalRevenue());
}
}
学习建议
- 基础案例:掌握Java基础语法、集合框架、面向对象编程
- 进阶案例:学习多线程、IO操作、异常处理
- 实用工具:练习文件操作、正则表达式、日期处理
- 设计模式:理解常见设计模式的应用场景
这些案例涵盖了Java开发中常用的技术和设计模式,建议按照从简到繁的顺序逐步学习实践。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播