作業內容:
練習一:
我的答案:
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();
}
}
}