gpt4 book ai didi

java - 使用断言来测试前提条件

转载 作者:搜寻专家 更新时间:2023-10-31 08:26:43 26 4
gpt4 key购买 nike

我正在做一项学校作业,我应该使用断言来测试存款方法和构造函数的前提条件。我想通了方法,但我仍然卡在如何添加到构造函数上。

这是我目前所拥有的:

/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount
{
private double balance;

/**
Constructs a bank account with a zero balance.
*/
public BankAccount()
{
balance = 0;
}

/**
Constructs a bank account with a given balance.
@param initialBalance the initial balance
*/
public BankAccount(double initialBalance)
{
balance = initialBalance;
}

/**
Deposits money into the bank account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
assert amount >=0;

double newBalance = balance + amount;
balance = newBalance;
}

/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
double newBalance = balance - amount;
balance = newBalance;
}

/**
Gets the current balance of the bank account.
@return the current balance
*/
public double getBalance()
{
return balance;
}
}

最佳答案

/**
Constructs a bank account with a zero balance.
*/
public BankAccount()
{
this(0);
}

/**
Constructs a bank account with a given balance.
@param initialBalance the initial balance
*/
public BankAccount(double initialBalance)
{
assert initialBalance >= 0;
balance = initialBalance;
}

创建任何非法的 BankAccount 会立即导致异常(如果启用断言)。

断言几乎可以放在代码的任何地方。它们用于调试目的,如果您禁用它们(例如在生产期间),它们将不起作用。

如果银行账户的目的是始终为正,您可能需要添加额外的断言,例如:

/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
assert amount <= this.balance;

this.balance -= amount;
}

再次声明,断言仅用于调试,您不应该 try catch 它们。任何断言异常都表明您的程序中存在错误(或断言语句中的错误)。

因此不应使用以下内容:

try
{
BankAccount newbankaccount = new BankAccount(5);
newbankaccount.withdraw(6.0);
}
catch (Exception e)
{
// illegal withdrawal
}

相反,您应该检查先决条件。

BankAccount newbankaccount = new BankAccount(5);
if (newbankaccount.getBalance() < 6.0)
{
// illegal withdrawal
}
else
newbankaccount.withdraw(6.0);

只有在您的应用程序中存在逻辑错误时才应触发断言异常。

关于java - 使用断言来测试前提条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18167641/

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