當前位置:編程學習大全網 - 編程語言 - java異常處理題,急~~在線等...

java異常處理題,急~~在線等...

下面的程序中定義了壹個用戶程序的異常InsuffivientFoundsException,這個異常用來處理帳戶資金不足的邏輯錯誤。

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();

}

}

  • 上一篇:高分懸賞,問問題。關於機械舞的。!
  • 下一篇:這個CAD裏的圓弧怎麽畫?
  • copyright 2024編程學習大全網