提问者:小点点

在达到极限之前,你如何继续增加双倍?


例如,我有一个银行账户,限额是500欧元。首先我加400欧元,然后再加150欧元。例如,如何更改代码以添加上次添加的100欧元,然后打印;“您的限额已达到(原150欧元)的限额(剩余50欧元),无法添加。”

我现在的代码是这样的;

private double limit;
private String name;
double deposit = 0;
double balance = 0;
int numberOfDeposits = 0;
double afhaling = 0;

public Bankaccount(String name, double limit) // constructor
{
    this.name = name;
    this.limit = limit;
}

public boolean addDeposit(double deposit){
    if(deposit < 0){
        balance = balance;
        return false;
    }
    
    if(deposit > 0){
        balance = balance + deposit;
        numberOfDeposits ++;
        return true;
    }
    
    if(balance > limit){
        balance = balance;
        return false;
    }
    return false;
}

共2个答案

匿名用户

就像我在评论中写的那样。在返回之前,您需要检查是否达到限制。这里有一个更好的函数:

public boolean addDeposit(double deposit){
        if(deposit <= 0){ // include the case for deposit == 0
            balance = balance; // is redundant
            return false;
        }else{
            balance = balance + deposit;

            if(balance > limit){
                balance = balance;
                System.out.print("Can not deposit because limit is reached.");
                return false;
            }else {
                numberOfDeposits++;
                return true;
            }
        }
    }

匿名用户

我对你的代码做了一些修改。让我知道这是否适合你。


  public class Bankaccount {
    private double limit;
    private String name;
    double deposit = 0;
    double balance = 0;
    int numberOfDeposits = 0;
    double afhaling = 0;

    public Bankaccount(String name, double limit) // constructor
    {
        this.name = name;
        this.limit = limit;
    }

    public boolean addDeposit(double deposit) {
        if (deposit <= 0) {
            return false;
        }

        var sum = balance + deposit;
        if (!(balance >= limit)) {
            if (balance != limit && sum > limit) {
                var amount = limit - balance;
                balance += amount;
                System.out.println("remaining amount " + (deposit - amount));
            } else if (balance != limit && sum < limit) {
                balance = sum; 
            }
            System.out.println("your new balance is " + balance);
            numberOfDeposits++;
            return true;
        } else {
            return false;
        }
    }

}