我正在创建一个具有这两种方法的程序,我无法弄清楚。它们是“撤回”和“存款”,它们位于CheckingAccount类中。在这些方法中,我想最初将值设为0然后添加到它。然后我想取新数字并从中减去。我想“存款”250美元。然后我想'退出'98美元。我不确定在哪里存储这些值以及如何执行它们。我有一个显示应该如何看待这个结尾,而我将撤销和存款方法留空。
帐户类:
class Account
{
protected string firstName;
protected string lastName;
protected long number;
public string FirstName
{
set
{
firstName = value;
}
}
public string LastName
{
set
{
lastName = value;
}
}
public long Number
{
set
{
number = value;
}
}
public override string ToString()
{
return firstName + " " + lastName + "\nAccount #: " + number;
}
}
}
检查帐户类:
class CheckingAccount : Account
{
private decimal balance;
public CheckingAccount(string firstName, string lastName, long number, decimal initialBalance)
{
FirstName = firstName;
LastName = lastName;
Number = number;
Balance = initialBalance;
}
public decimal Balance
{
get
{
return balance;
}
set
{
balance = value;
}
}
public void deposit(decimal amount)
{
//initial value should be 0 and should be adding 250 to it.
}
public void withdraw(decimal amount)
{
//this takes the 250 amount and subtracts 98 from it
}
public void display()
{
Console.WriteLine(ToString());
Console.WriteLine("Balance: ${0}", Balance);
}
}
}
展示班级:
class Display
{
static void Main(string[] args)
{
CheckingAccount check = new CheckingAccount("John", "Smith", 123456, 0M);
Console.WriteLine("After Account Creation...");
check.display();
Console.WriteLine("After Depositing $250...");
//constructor
Console.WriteLine("After Withdrawing $98...");
//constructor
}
}
}
我希望我的输出看起来像这样:
创建帐户后...
约翰史密斯
帐号:123456
余额:0
存款250美元后......
约翰史密斯
帐号:123456
余额:250左
扣除98美元后...
约翰史密斯
帐号:123456
余额:152
答案 0 :(得分:5)
简单的答案是
public void deposit(decimal amount)
{
balance += amount;
}
public void withdraw(decimal amount)
{
balance -= amount;
}
随意添加必要的验证(透支?尝试存入负数?)
答案 1 :(得分:1)
创建帐户:
Checking Account ca = new Checking Account (John, Smith, 123456, 0);
存入250美元:
ca.deposit(250);
提取98美元:
ca.withdraw(98);
业务逻辑:
public void deposit(decimal amount)
{
balance += amount;
}
public void withdraw(decimal amount)
{
balance -= amount;
}
与其他answer州一样,当您的帐户中没有金钱(或更少)时,验证诸如透支或撤销等情况是明智的。
奖金:
您还可以编写GetBalance函数来验证存款/取款。
public decimal GetBalance(long accountNumber)
{
return balance;
}
并使用以下方式调用它:
var currentBalance = ca.GetBalance(123456);
答案 2 :(得分:1)
您可能希望为withdraw方法提供其他逻辑以防止过度删除。
public void withdraw(decimal amount)
{
if (balance >= amount)
{
balance -= amount;
}
else
{
Console.WriteLine("You can't withdraw money that you don't have!");
// or else you could charge an overdraft fee as long as you're within
// a certain tolerance (minimum of -1000 or something like that).
}
}