public class BankAccount{
int AccountNumber; //賬號
double Account; //
double income; //收入
double payout; // 支出
BankAccount(int accNo,double in,double out){ //構造函數,獲得賬號、收入和支出數目
this.AccountNumber=accNo;
this.income=in;
this.payout=out;
}
int getAccountNumber(){
return AccountNumber;
}
boolean Balance(){
if((income-payout)>0)
return true;
else return false;
}
boolean isBalance()throws InsufficientFoundsException{ //收支平衡
if(this.Balance())
return true;
else{
throw new InsufficientFoundsException(this,(income-payout));
}
}
public static void main(String args[]){
BankAccount bankAcc1=new BankAccount(1001,100,50);//創建第壹個對象
BankAccount bankAcc2=new BankAccount(1002,100,300);//創建第二個對象
try{
if(bankAcc1.isBalance()) //如果收支平衡 就顯示“ok!”
System.out.println("account:"+bankAcc1.getAccountNumber()+" ok!");
if(bankAcc2.isBalance())
System.out.println("account:"+bankAcc1.getAccountNumber()+" ok!");
}
catch(InsufficientFoundsException i){ //捕獲
System.out.println(i.toString());
}
}
}
//自定義的異常處理類
class InsufficientFoundsException extends Exception {
private BankAccount m_ba;
private double getAmount;
InsufficientFoundsException(BankAccount ba,double dAmount){
super("Insufficient founds in account");
m_ba=ba;
getAmount=dAmount;
}
public String toString(){
StringBuffer sb=new StringBuffer();
sb.append("Insufficient founds in account:");
sb.append(m_ba.getAccountNumber());
sb.append("\nBalance was:");
sb.append(m_ba.Balance());
sb.append("\ngetAmount was: ");
sb.append(getAmount);
return sb.toString();
}
}