What's wrong with the code?

  • Thread starter Thread starter BenTam
  • Start date Start date
B

BenTam

Guest
Could anybody tell me what's wrong with the following code?

1626041.gif

The code segments are copied from Microsoft's C# Tutorial.

using System;

namespace Inherit3
{
class Program
{
static void Main(string[] args)
{
BankAccount account = new BankAccount("Ben", 10000);
account.MakeWithdrawal(500, DateTime.Now, "Rent payment");
Console.WriteLine(account.Balance);
account.MakeDeposit(100, DateTime.Now, "Friend paid me back");
Console.WriteLine(account.Balance);
account.GetAccountHistory();
Console.WriteLine(account.Report);
}

}
}



using System;
using System.Collections.Generic;

namespace Inherit3
{
public class Transaction
{
public decimal Amount { get; }
public DateTime Date { get; }
public string Notes { get; }
public Transaction(decimal amount, DateTime date, string note)
{
this.Amount = amount;
this.Date = date;
this.Notes = note;
}
}
public class BankAccount
{
public string Report { get; set; }
public decimal InitialBalance { get; set; }
public string Number { get; }
public string Owner { get; set; }
public decimal Balance
{
get
{
decimal balance = InitialBalance;
foreach (var item in allTransactions)
{
balance += item.Amount;
}
return balance;
}
}
private List<Transaction> allTransactions = new List<Transaction>();
private static int accountNumberSeed = 1234567890;
public virtual void PerformMonthEndTransactions() { }
public BankAccount(string name, decimal initialBalance)
{
this.Number = accountNumberSeed.ToString();
accountNumberSeed++;
this.Owner = name;
MakeDeposit(initialBalance, DateTime.Now, "Initial balance");
}
public void MakeDeposit(decimal amount, DateTime date, string note)
{
if (amount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(amount), "Amount of deposit must be positive");
}
var deposit = new Transaction(amount, date, note);
allTransactions.Add(deposit);
}

public void MakeWithdrawal(decimal amount, DateTime date, string note)
{
if (amount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(amount), "Amount of withdrawal must be positive");
}
if (Balance - amount < 0)
{
throw new InvalidOperationException("Not sufficient funds for this withdrawal");
}
var withdrawal = new Transaction(-amount, date, note);
allTransactions.Add(withdrawal);
}

public string GetAccountHistory()
{
var report = new System.Text.StringBuilder();
decimal balance = 0;
report.AppendLine("Date\t\tAmount\tBalance\tNote");
foreach (var item in allTransactions)
{
balance += item.Amount;
report.AppendLine($"{item.Date.ToShortDateString()}\t{item.Amount}\t{balance}\t{item.Notes}");
}
this.Report += report.ToString();
return this.Report;

}
}
}

Continue reading...
 
Back
Top