[英]Java Math.max for Bank Account Transactions
所以,我有這個問題,我一直在努力的目標是為銀行賬戶中的每筆交易扣除超過分配數量的免費交易的費用。 到目前為止,我已經掌握了計算交易的所有內容,但我們應該與Math.max合作,以便當您查看免費交易金額時,費用開始從余額中減去帳戶。 我在我的deductMonthlyCharge方法中使用Math.max。 我想我知道如何用if和else語句來做這個,但是我們不允許在這里使用它們而且我對Math.max不是很熟悉。 所以,如果有人能指出我正確的方向來解決這個問題,那就太好了。 謝謝。
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
public class BankAccount
{
private double balance;
private double fee;
private double freeTransactions;
private double transactionCount;
/**
Constructs a bank account with a zero balance
*/
public BankAccount()
{
balance = 0;
fee = 5;
freeTransactions = 5;
transactionCount = 0;
}
/**
Constructs a bank account with a given balance
@param initialBalance the initial balance
*/
public BankAccount(double initialBalance)
{
balance = initialBalance;
transactionCount = 0;
}
public static void main(String [ ] args)
{
BankAccount newTransaction = new BankAccount();
newTransaction.deposit(30);
newTransaction.withdraw(5);
newTransaction.deposit(20);
newTransaction.deposit(5);
newTransaction.withdraw(5);
newTransaction.deposit(10);
System.out.println(newTransaction.getBalance());
System.out.println(newTransaction.deductMonthlyCharge());
}
public void setTransFee(double amount)
{
balance = amount+(balance-fee);
balance = balance;
}
public void setNumFreeTrans(double amount)
{
amount = freeTransactions;
}
/**
Deposits money into the bank account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
double newBalance = balance + amount;
balance = newBalance;
transactionCount++;
}
/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
double newBalance = balance - amount;
balance = newBalance;
transactionCount++;
}
public double deductMonthlyCharge()
{
Math.max(transactionCount, freeTransactions);
return transactionCount;
}
/**
Gets the current balance of the bank account.
@return the current balance
*/
public double getBalance()
{
return balance;
}
}
max(double, double)
返回灌漿者的雙倍值。 只是改變
Math.max(transactionCount, freeTransactions);
return transactionCount;
至
return Math.max(transactionCount, freeTransactions);
如果你想要返回更大的值。
double,就像所有原始類型都沒有像對象一樣的引用。 你需要像double foo = functionThatReturnPrimitiveDouble()
一樣保存返回的值,或者像我在上面的例子中那樣再次返回它。
我想你想要這樣的東西(假定每筆交易超過允許金額的費用為1.00美元):
public double deductMonthlyCharge()
{
int transCount = Math.max(transactionCount, freeTransactions);
double fee = 1.00 * (transCount - freeTransactions);
return fee;
}
如果客戶沒有超過他們允許的免費交易數量,那么(transCount - freeTransactions)
將為0,因此不收取任何費用。
這段代碼對於它自己的好處來說有點過於聰明,但我認為這就是古怪的要求(不要使用if語句,使用max代替)。
更清楚(但相當)將是:
public double deductMonthlyCharge()
{
if (transactionCount > freeTransactions) {
return 1.00 * (transactionCount - freeTransactions);
}
return 0.0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.