作业内容:
练习一:
我的答案:
package expenction;
public class OverDraftException extends Exception{
// 透支额度
private double deficit;
public OverDraftException(String message, double deficit){
super(message);
this.deficit = deficit;
}
public double getDeticit() {
return deficit;
}
}
//------------------------------------------
package expenction;
public class Account {
// 属性-余额
protected double balance;
// 构造方法
public Account(double init){
this.balance = init;
}
// 方法,获取余额
public double getBlance(){
return balance;
}
// 方法,存钱
public void deposit(double amt){
this.balance += amt;
}
/**
* 以下是不会的点
*/
// 方法,取钱
// 同时,如果余额小于取钱数,抛出余额不足的错误
public void withdraw(double amt) throws OverDraftException{
if(this.balance<amt){
throw new OverDraftException("余额不足", amt - this.balance);
}
this.balance -= amt;
}
// 这是第一遍自己写的,问题比较大
// public void withcdraw(double amt){
// balance -= amt;
// }
}
//-----------------------------------
/**
* 不太会写这个mian函数
*/
package expenction;
public class Test {
public static void main(String[] args) {
// 开设账户,存入1000元(根据自定义构造方法,构造Account类,指向a)
Account a = new Account(1000);
// 存入1000元
a.deposit(1000);
// 查看余额
System.out.println(a.getBlance());
// 以下是重点
try{
// 在余额仅有2000元的情况下,取2001元
a.withdraw(2001);
} catch(OverDraftException err) {
System.out.println("看到这句就代表有毛病了!");
System.err.println("透支金额:" + err.getDeticit());
err.printStackTrace(); // 该语句会打印出方法调用的痕迹
}
}
作业心得:
学习了try, catch, throw, throws的用法。以及作业中为使用的finally,无论如何都会运行的代码块。
练习二:
我的答案:
package expenction;
public class CheckingAccount extends Account {
// 透支额度
private double overdraftProtection;
// 创建一个普通账户
public CheckingAccount(double balance){
super(balance);
}
// 创建一个具有透支额度的账户
public CheckingAccount(double balance, double protect){
super(balance);
this.overdraftProtection = protect;
}
// 取款
public void withdraw(double amt) throws OverDraftException {
if( Math.abs(this.balance - amt) > this.overdraftProtection ){
throw new OverDraftException("透支额度不足",amt - (this.balance + this.overdraftProtection) );
}
this.balance -= amt;
}
}
//------------------------------------
package expenction;
public class Test {
public static void main(String[] args) {
//
// // 开设账户,存入1000元(根据自定义构造方法,构造Account类,指向a)
// Account a = new Account(1000);
// // 存入1000元
// a.deposit(1000);
//
// // 查看余额
// System.out.println(a.getBlance());
//
//
// // 以下是重点
// try{
// // 在余额仅有2000元的情况下,取2001元
// a.withdraw(2001);
// } catch(OverDraftException err) {
// System.out.println("看到这句就代表有毛病了!");
// System.err.println("透支金额:" + err.getDeticit());
// err.printStackTrace(); // 该语句会打印出方法调用的痕迹
// }
//
CheckingAccount ca = new CheckingAccount(1000, 500);
ca.deposit(1000);
System.out.println(ca.getBlance());
try{
ca.withdraw(2501);
} catch(OverDraftException err) {
System.err.println("透支额度:" + err.getDeticit());
err.printStackTrace();
}
}
}