Browse Source

上传文件至 'w7'

main
Chengwuyi 3 weeks ago
parent
commit
9871308a24
  1. 84
      w7/BankAccount.java
  2. 75
      w7/ScoreReader.java

84
w7/BankAccount.java

@ -0,0 +1,84 @@
/**
* 任务二银行取款自定义异常
* 文件内含InsufficientFundsException + Account + main 测试
*/
// ── 自定义异常:继承 Exception(Checked,强迫调用方处理)──
class InsufficientFundsException extends Exception {
private final double balance; // 当前余额
private final double amount; // 尝试取款金额
public InsufficientFundsException(double balance, double amount) {
super(String.format("余额不足!当前余额 %.2f 元,尝试取款 %.2f 元,差额 %.2f 元",
balance, amount, amount - balance));
this.balance = balance;
this.amount = amount;
}
public double getBalance() { return balance; }
public double getAmount() { return amount; }
}
// ── Account 类 ──
class Account {
private final String owner;
private double balance;
public Account(String owner, double initialBalance) {
this.owner = owner;
this.balance = initialBalance;
}
/**
* 取款余额不足时抛出 InsufficientFundsException并携带当前余额信息
*/
public void withdraw(double amount) throws InsufficientFundsException {
if (amount <= 0) {
throw new IllegalArgumentException("取款金额必须大于 0");
}
if (amount > balance) {
throw new InsufficientFundsException(balance, amount);
}
balance -= amount;
System.out.printf(" 取款成功:%.2f 元,剩余余额:%.2f 元%n", amount, balance);
}
public double getBalance() { return balance; }
public String getOwner() { return owner; }
}
// ── 测试入口 ──
public class BankAccount {
public static void main(String[] args) {
Account acc = new Account("张三", 500.00);
System.out.println("账户:" + acc.getOwner() + ",初始余额:" + acc.getBalance());
// 正常取款
System.out.println("\n--- 取款 200 元 ---");
try {
acc.withdraw(200);
} catch (InsufficientFundsException e) {
System.out.println(" 提示:" + e.getMessage());
}
// 余额不足
System.out.println("\n--- 取款 400 元(余额不足)---");
try {
acc.withdraw(400);
} catch (InsufficientFundsException e) {
System.out.println(" 提示:" + e.getMessage());
System.out.printf(" 当前余额:%.2f 元,建议最多取 %.2f 元%n",
e.getBalance(), e.getBalance());
}
// 非法金额
System.out.println("\n--- 取款 -50 元(非法金额)---");
try {
acc.withdraw(-50);
} catch (InsufficientFundsException e) {
System.out.println(" 提示:" + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println(" 错误:" + e.getMessage());
}
}
}

75
w7/ScoreReader.java

@ -0,0 +1,75 @@
import java.io.*;
import java.nio.file.*;
/**
* 课堂练习重构"裸奔"代码
* 使用 try-with-resources 确保流自动关闭处理三类异常
*/
public class ScoreReader {
public static void main(String[] args) {
// 创建一个测试用的 scores.txt(实际场景中文件已存在)
createSampleFile();
System.out.println("=== 正常读取 ===");
readAndPrintAverage("scores.txt");
System.out.println("\n=== 文件不存在 ===");
readAndPrintAverage("notfound.txt");
System.out.println("\n=== 含非数字行 ===");
createBadFile();
readAndPrintAverage("bad_scores.txt");
}
/**
* 重构后的核心方法
* 1. try-with-resources 自动关闭流无需手动 br.close()
* 2. 分层处理三类异常文件不存在 / 读取错误 / 数字格式错误
*/
public static void readAndPrintAverage(String filename) {
int sum = 0;
int count = 0;
// try-with-resources:括号内声明的资源在 try 结束后自动关闭
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) continue; // 跳过空行
try {
sum += Integer.parseInt(line); // 可能抛 NumberFormatException
count++;
} catch (NumberFormatException e) {
System.out.println(" 警告:跳过非数字行 [" + line + "]");
}
}
} catch (FileNotFoundException e) {
System.out.println(" 错误:文件不存在 -> " + filename);
return;
} catch (IOException e) {
System.out.println(" 错误:文件读取失败 -> " + e.getMessage());
return;
}
if (count == 0) {
System.out.println(" 无有效成绩数据。");
} else {
System.out.printf(" 共 %d 条成绩,平均分:%.2f%n", count, (double) sum / count);
}
}
// ── 辅助:生成测试文件 ──
private static void createSampleFile() {
try (PrintWriter pw = new PrintWriter("scores.txt")) {
pw.println("85"); pw.println("92");
pw.println("78"); pw.println("90"); pw.println("88");
} catch (IOException ignored) {}
}
private static void createBadFile() {
try (PrintWriter pw = new PrintWriter("bad_scores.txt")) {
pw.println("75"); pw.println("abc"); pw.println("88");
} catch (IOException ignored) {}
}
}
Loading…
Cancel
Save