我如何创建一种可以检查帐户中是否有足够资金以允许提款或资金不足的方法

时间:2019-05-19 23:36:31

标签: java

这是我到目前为止所拥有的。 如何获得添加提款的方法,该方法接收提款金额作为参数。我希望此方法还可以检查帐户中是否有足够的资金以允许提款。如果资金不足,则该方法应显示消息“此提款资金不足”。

UnauthorizedAccessException

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您已经拥有withdrawl方法:

public float withdrawel(float num2)

您还可以访问所有信息来执行计算:

public float withdrawel(float num2) {
    float with = num2;
    if (this.balance < with){
        System.out.println( "Insufficient funds ( " 
            + this.balance + ") for this withdrawal " + with);
    }
    else {
        this.balance -= with;
    }
    return this.balance;
}

使用此方法,您现在可以尝试从帐户中提取不同的金额:

public static void main(String [] args){
    int acctnum = 1971;
    float acctbal = (float) 198.45;
    float withdrawl1 = (float) 500.50;  # should throw Insufficient Funds message 
    float withdrawl2 = (float) 20.50;   # should successfully withdrawl

    CurrentAccount ca = new CurrentAccount(acctnum, acctbal);

    System.out.println("Account " + acctnum + ": " + ca.getBalance());
    ca.withdrawel(withdrawl1);
    System.out.println("End Balance: " + ca.getBalance());
    ca.withdrawel(withdrawl2);
    System.out.println("End Balance: " + ca.getBalance());
}

演示:

Account 1971: 198.45
Insufficient funds ( 198.45) for this withdrawal 500.5
End Balance: 198.45
End Balance: 177.95