gpt4 book ai didi

java - 如何返回并置零?

转载 作者:行者123 更新时间:2023-11-30 06:19:09 26 4
gpt4 key购买 nike

我想问一个问题。如果金额大于余额,我必须退还全部余额并将余额设置为零。我该怎么做?我尝试了很多不同的方法来解决这个问题,但没有奏效。感谢您的帮助。

public class BankAccount {
double balance;

BankAccount(double openingBalance){
balance=openingBalance;
}
public double getBalance(){
return balance;
}
public void deposit(double amount){
balance += amount;
}
public double withdraw (double amount){
if (balance > amount){
balance -= amount;
}else if (amount > balance || amount == balance){
**return balance;
balance = 0**
}
return amount;
}
}

驱动类

public class Driver {

static BankAccount acc3;

public static void main (String[] args){
BankAccount acc3 = new BankAccount ("Alana","Neil", 5000);
System.out.println("\nName: " +acc3.Name());
System.out.println("Amount: $" +acc3.balance);
acc3.deposit(100);
System.out.println("Deposit Amount: $" +acc3.balance);
System.out.println("Withdrawl Amount: $"+acc3.withdraw(5400));
System.out.println("The New Balance: $" +acc3.balance);

}
}

最佳答案

使用临时变量:

double tmp = balance;
balance = 0;
return tmp;

关于java - 如何返回并置零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23573915/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com