C# Using child class methods on an array of objects [duplicate] - c#

This question already has an answer here:
calling child class method from base class C#
(1 answer)
Closed 5 years ago.
I'm sure I'm missing something minor but I can't for the life of me figure it out. I'm trying to use the child class method CalculateInterest for child class SavingsAccount and the child class property TransactionFee for the child class CheckingAccount in the below script. Basically, the test program should loop through each object in the array and depending upon whether the object is a CheckingAccount or SavingsAccount state the interest earned or the transaction fee charged.
The error I get is that CalculateInterest() and TransactionFee are not defined in class Account.
using System;
class BankAccountTester {
static void Main() {
Account[] accounts = new Account[4];
accounts[0] = new SavingsAccount(25, 3);
accounts[1] = new CheckingAccount(80, 1);
accounts[2] = new SavingsAccount(200, 1.5);
accounts[3] = new CheckingAccount(400, 0.5);
for (int i = 0; i < 4; i++) {
double amount;
string entryString;
bool check = false;
Console.WriteLine("Enter an amount to withdraw from Account " + i );
entryString = Console.ReadLine();
check = double.TryParse(entryString, out amount);
while (check == false) {
Console.WriteLine("Invalid entry. Please specify an amount to withdraw from Account " + i);
entryString = Console.ReadLine();
check = double.TryParse(entryString, out amount);
}
accounts[i].Debit(amount);
Console.WriteLine("Enter an amount to deposit into Account " + i);
entryString = Console.ReadLine();
check = double.TryParse(entryString, out amount);
while (check == false) {
Console.WriteLine("Invalid entry. Please specify an amount to deposit into Account " + i);
entryString = Console.ReadLine();
check = double.TryParse(entryString, out amount);
}
accounts[i].Credit(amount);
if (accounts[i] is SavingsAccount) {
Console.WriteLine("This is a savings account.");
double interestEarned = accounts[i].CalculateInterest();
Console.WriteLine("Adding {0} interest to Account {2} (Savings Account)", interestEarned, i);
}
else {
Console.WriteLine("This is a checking account.");
Console.WriteLine("{0} transaction fee charged.", accounts[i].TransactionFee);
}
}
}
}
class Account {
private double balance;
public double Balance {
get {
return balance;
}
set {
if (value<0) {
balance = 0;
}
else balance = value;
}
}
public Account(double initBalance) {
Balance = initBalance;
}
public void Credit(double amount) {
Balance = Balance + amount;
}
public void Debit(double amount) {
if (amount>Balance) {
Console.WriteLine("Amount exceeds account balance.");
}
else Balance = Balance - amount;
}
}
class SavingsAccount : Account {
private double interestRate;
private double interestEarned;
public SavingsAccount(double initBalance, double interest) : base(initBalance) {
interestRate = interest/100;
}
public double CalculateInterest() {
interestEarned = Balance*interestRate;
return interestEarned;
}
}
class CheckingAccount : Account {
private double transactionFee;
public double TransactionFee {
get {
return transactionFee;
}
set {
transactionFee = value;
}
}
public CheckingAccount(double initBalance, double fee) : base(initBalance) {
TransactionFee = fee;
}
public new void Credit(double amount) {
Balance = Balance + amount;
Balance = Balance - TransactionFee;
}
public new void Debit(double amount) {
bool check;
if (amount>Balance) {
Console.WriteLine("Amount exceeds account balance.");
check = false;
}
else {
Balance = Balance - amount;
check = true;
}
if (check == true) {
Balance = Balance - TransactionFee;
}
else Balance = Balance;
}
}

You need to cast the objects to the more specialized type first, before you can use the methods:
Change this:
double interestEarned = accounts[i].CalculateInterest();
To this:
double interestEarned = ((SavingsAccount)accounts[i]).CalculateInterest();
Change this:
Console.WriteLine("{0} transaction fee charged.", accounts[i].TransactionFee);
To this:
Console.WriteLine("{0} transaction fee charged.", ((CheckingAccount)accounts[i]).TransactionFee);

Related

Array won't output anything

Doing a school activity but I hit a roadblock. I can't seem to make the program output the arrays I've entered. The output works when the variables inside the PlayerCharacter() and Mage() were all regular variables. Then I turned them into arrays because that was what was required of us, but then it started not showing anything during output.
using System;
namespace Summative
{
class PlayerCharacter
{
string[] name = new string[10];
int[] life = new int[10];
char[] gender = new char[10];
public int i = 0;
public int x = 0;
public PlayerCharacter()
{
Console.Write("Enter character name: ");
this.Name = Console.ReadLine();
Console.Write("Enter Life: ");
this.Life = int.Parse(Console.ReadLine());
Console.Write("Enter Gender (M/F): ");
this.Gender = char.Parse(Console.ReadLine());
i++;
}
public string Name
{
get
{
return name[i];
}
set
{
name[i] = value;
}
}
public int Life
{
get
{
return life[i];
}
set
{
life[i] = value;
}
}
public char Gender
{
get
{
return gender[i];
}
set
{
if (value == 'M' || value == 'F')
{
gender[i] = value;
}
else
{
Console.WriteLine("Invalid Gender!");
}
}
}
public virtual void Output()
{
Console.WriteLine("Name: " + string.Join(",", Name));
Console.WriteLine("Life: " + string.Join(",", Life));
Console.WriteLine("Gender: " + string.Join(",", Gender));
}
}
class Mage : PlayerCharacter
{
string[] element = new string[10];
int[] mana = new int[10];
public Mage() : base()
{
Console.Write("Enter element: ");
this.Elements = Console.ReadLine();
Console.Write("Enter mana: ");
this.Mana = int.Parse(Console.ReadLine());
}
public string Elements
{
get
{
return element[x];
}
set
{
element[x] = value;
}
}
public int Mana
{
get
{
return mana[x];
}
set
{
mana[x] = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Element: " + string.Join(",", Elements));
Console.WriteLine("Mana: " + string.Join(",", Mana));
x++;
}
}
class Rogue : PlayerCharacter
{
string faction;
float energy;
public Rogue() : base()
{
Console.Write("Enter faction name: ");
this.Faction = Console.ReadLine();
Console.Write("Enter energy: ");
this.Energy = float.Parse(Console.ReadLine());
}
public string Faction
{
get
{
return faction;
}
set
{
faction = value;
}
}
public float Energy
{
get
{
return energy;
}
set
{
energy = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Faction: " + Faction);
Console.WriteLine("Energy: " + Energy);
}
}
class Fighter : PlayerCharacter
{
string weapon;
double strength;
public Fighter() : base()
{
Console.Write("Enter weapon name: ");
this.Weapon = Console.ReadLine();
Console.Write("Enter strength: ");
this.Strength = double.Parse(Console.ReadLine());
}
public string Weapon
{
get
{
return weapon;
}
set
{
weapon = value;
}
}
public double Strength
{
get
{
return strength;
}
set
{
strength = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Weapon: " + Weapon);
Console.WriteLine("Strength: " + Strength);
}
}
class TestPlayer
{
static void Main(string[] args)
{
PlayerCharacter character;
CharacterCreator:
int switchchoice = 0;
Console.WriteLine("Select a class");
Console.WriteLine("1. Mage");
Console.WriteLine("2. Rogue");
Console.WriteLine("3. Fighter");
Console.WriteLine("0. Exit");
Console.Write("Enter Choice: ");
start:
try
{
switchchoice = int.Parse(Console.ReadLine());
}
catch
{
Console.Clear();
Console.WriteLine("Invalid Input! Please Try Again.");
goto CharacterCreator;
}
switch (switchchoice)
{
case 1:
Console.Clear();
character = new Mage();
character.Output();
break;
case 2:
Console.Clear();
character = new Rogue();
character.Output();
break;
case 3:
Console.Clear();
character = new Fighter();
character.Output();
break;
case 0:
Console.Clear();
goto start;
default:
Console.Clear();
Console.WriteLine("Invalid Input! Please Try Again.");
goto CharacterCreator;
}
int choice;
int y = 0;
int z;
int i = character.i;
int x = character.x;
Console.Clear();
Console.WriteLine("Player Character Designer");
Console.WriteLine("1. Create");
Console.WriteLine("2. View");
Console.Write("Enter Choice: ");
choice = int.Parse(Console.ReadLine());
if (choice == 1)
{
goto CharacterCreator;
}
else if (choice == 2)
{
z = i;
i = 0;
x = 0;
do
{
character.Output();
Console.WriteLine(" ");
y++;
i++;
x++;
} while (y != z);
}
}
}
}
Answer: Use a list
The main issue is that you should add the created characters in a list rather than keeping arrays of attributes inside characters. This lets you loop over each character and print all the information in turn. I.e.
var myCharacters = new List<PlayerCharacter>();
...
myCharacters.Add(myCharacter);
Other Issues
Constructors & object design
Inject parameters in constructors whenever possible, and use auto-properties when applicable. This helps avoid complex logic in the constructors, and reduces the size of the classes. Let the creator of the characters be responsible for reading the necessary parameters. I would also prefer to separate the construction of the information-string and the output, that way you can output the same information to a log file or whatever, and not just to the console. I.e:
class PlayerCharacter
{
public string Name { get; }
public int Life { get; }
public string Gender { get; }
public PlayerCharacter(string name, int life, string gender)
{
Name = name;
Life = life;
Gender = gender;
}
public override string ToString()
{
return $"Name: {Name}, Life {Life}, Gender: {Gender}";
}
}
Control flow
Use loops instead of goto. While I think there are cases where goto is the best solution, they are rare, and the general recommendation is to use loops for control flow i.e. something like this pseudocode
MyOptions option;
var myCharacters = new List<PlayerCharacter>();
do{
myCharacters.Add(ReadCharacter());
option = ReadOption();
}
while(option != MyOptions.ViewCharacters);
PrintCharacters(myCharacters);
Split code into methods
Move code into logical functions, especially for repeated code. This helps to make it easier to get a overview of the program. For example, for reading numbers it is better to use the TryParse function than trying to catch exceptions, and put it in a method to allow it to be reused:
int ReadInteger()
{
int value;
while (!int.TryParse(Console.ReadLine(), out value))
{
Console.WriteLine("Invalid Input! Please Try Again.");
}
return value;
}

Adding Interest Rate and Overdraft Fee to banking system

This is what I'm trying to achieve:
If a request is made to withdraw money over and above the allowed overdraft limit ($100), then no money is withdrawn, and a fixed flat fee ($10) is deducted from the balance.
In the code below I have tried my best to do so but it isn't working as when I withdraw an amount over my balance it doesn't give me a failed transaction fee it instead gives me a negative balance. I'm also unsure of how when the user clicks the Account details they want to see I want it to display the failed transaction fee if there is any if the user went over the overdraft.
Any help will be much appreciated. Just cant get my head around it.
class Program
{
class Customer
{
private string firstName;
private string lastName;
private int phoneNumber;
private string address;
public Customer()
{
firstName = "Tayla";
lastName = "Brown";
phoneNumber = 027493922;
address = "55 Grey Rd";
}
//client info
public string ClientInfo()
{
string clientinfo = ("Account Holder: " + firstName + " " + lastName + " " + "Phone Number: " + phoneNumber + " " + "Address: " + address);
return clientinfo;
}
}
class Account : Customer
{
// Fields
private double accountNumber;
protected string accountType;
protected double balance;
protected double deposit;
protected double withdrawal;
protected double interest;
protected double fee;
protected double overdraft;
// Properties
public string AccountType
{
get { return this.accountType; }
}
public double Withdrawal
{
get { return this.withdrawal; }
set { this.withdrawal = value; }
}
public double Deposit
{
get { return this.deposit; }
set { this.deposit = value; }
}
public double AcctNumber
{ get { return this.accountNumber; } }
public double Bal
{ get { return this.balance; } }
public double f
{ get { return this.fee; } }
public double od
{ get { return this.overdraft; } }
// Creating Random Account Number
public virtual double AccountNumb()
{
Random rand = new Random();
this.accountNumber = rand.Next(100000000, 1000000000);
return accountNumber;
}
public virtual double Fee() // Work out Fee
{
overdraft = 100;
fee = 10;
if (balance < withdrawal)
{
balance -= (overdraft + withdrawal);
}
else if (balance > withdrawal)
{
balance -= withdrawal;
fee -= balance;
}
return balance;
}
//Computes General Balance(resets values)
public virtual double Balance()
{
balance = balance + deposit - withdrawal;
deposit = 0;
withdrawal = 0;
return balance;
}
//Computers Balance when withdrawal equals zero
public virtual double DepositBalance(double input)
{
deposit = input;
withdrawal = 0;
balance = balance + deposit - withdrawal;
return balance;
}
//Computers balance when deposit equals zero
public virtual double WithBalance(double input)
{
withdrawal = input;
deposit = 0;
balance = balance + deposit - withdrawal;
return balance;
}
//displays online banking menu
public virtual void DisplayMenu()
{
Console.WriteLine("Welcome to your online bank account\nPlease choose from the options below: ");
Console.WriteLine("");
Console.WriteLine("1.View Client Info");
Console.WriteLine("");
Console.WriteLine("2. View Account Balance:");
Console.WriteLine(" 2A.Everyday\n 2B.Investment\n 2C.Omni");
Console.WriteLine("");
Console.WriteLine("3.Deposit Funds:\n 3A.Everyday\n 3B.Investment\n 3C.Omni");
Console.WriteLine("");
Console.WriteLine("4.Withdraw Funds:\n 4A.Everyday\n 4B.Investment\n 4C.Omni");
Console.WriteLine("");
Console.WriteLine("5.View Everyday Banking Details");
Console.WriteLine("6.View Investment Banking Details");
Console.WriteLine("7.View Omni Banking details");
Console.WriteLine("");
Console.WriteLine("8.Exit");
}
}
// Everyday Account
class Everyday : Account
{
//field
private double minBalance;
private double maxBalance;
//properties
public double MinBalance
{ get { return this.minBalance; } }
public double MaxBalance
{ get { return this.maxBalance; } }
//constructors
public Everyday(double balance) : base()
{
this.minBalance = 0;
this.maxBalance = 1000000000000;
this.balance = balance;
accountType = "Everyday Account";
}
//methods
}
// Investment Account
class Investment : Account
{
//fields
private int investmentInterest;
private int feeInvestment;
//properties
public int InterestInvestment
{
get { return this.investmentInterest; } // Sets Interest
set { investmentInterest = 4; }
}
public int FeeInvestment
{
get { return this.feeInvestment; } // Sets Fee
set { feeInvestment = 10; }
}
//constructors
public Investment(double balance) : base()
{
this.balance = balance;
accountType = "Investment Account";
}
//methods
}
// Omni Account
class Omni : Account // If a request is made to withdraw money over and above the allowed overdraft limit, then no money is withdrawn and
// a fixed flat fee is deducted from the balance
{
//fields
private int interestOmni;
private int overdraft;
//properties
public int InterestOmni
{
get { return this.interestOmni; } // Get interest
set { interestOmni = 4; }
}
public int OverDraftOmni
{
get { return this.overdraft; } // Get overdraft
}
//constructors
public Omni(double balance) : base()
{
interestOmni = 4;
overdraft = 1000; // Overdraft same as min balance?
this.balance = balance;
accountType = "Omni Account";
}
}
static void Main(string[] args)
{
// Object Insantiating
Account client = new Account(); // Our one client
Everyday everyday = new Everyday(2000);
everyday.AccountNumb();
Investment investment = new Investment(500);
investment.AccountNumb();
Omni omni = new Omni(1000);
omni.AccountNumb();
string streamEverydayAccount = ("Account Number: " + everyday.AcctNumber);
string streamInvestmentAccount = ("Account Number: " + investment.AcctNumber);
string streamOmniAccount = ("Account Number: " + omni.AcctNumber);
string streamClientInfo = (client.ClientInfo());
string everydayAccountType = (everyday.AccountType);
string investmentAccountType = (everyday.AccountType);
string omniAccountType = (everyday.AccountType);
// StreamWriter Everyday Account
using (StreamWriter everydaysummary = new StreamWriter(#"EverydaySummary.txt", true))
{
everydaysummary.WriteLine(everydayAccountType);
everydaysummary.WriteLine(streamClientInfo);
everydaysummary.WriteLine(streamEverydayAccount);
}
// StreamWriter Investment Account
using (StreamWriter investmentsummary = new StreamWriter(#"InvestmentSummary.txt", true))
{
investmentsummary.WriteLine(investmentAccountType);
investmentsummary.WriteLine(streamClientInfo);
investmentsummary.WriteLine(streamInvestmentAccount);
}
// StreamWriter Omni Account
using (StreamWriter omnisummary = new StreamWriter(#"OmniSummary.txt", true))
{
omnisummary.WriteLine(omniAccountType);
omnisummary.WriteLine(streamClientInfo);
omnisummary.WriteLine(streamOmniAccount);
}
bool test = false;
do
{
string everydayDepositPara = ($"Transaction: +${everyday.Deposit} at {DateTime.Now.ToString()} Current Balance: ${everyday.Bal}");
string everdayWithdrawalPara = ($"Transaction: -${everyday.Withdrawal} at {DateTime.Now.ToString()} Current Balance: ${everyday.Bal}");
string investmentDepositPara = ($"Transaction: +${investment.Deposit} at {DateTime.Now.ToString()} Current Balance: ${investment.Bal}");
string investmentWithdrawalPara = ($"Transaction: -${investment.Withdrawal} at {DateTime.Now.ToString()} Current Balance: ${investment.Bal}");
string omniDepositPara = ($"Transaction: +${omni.Deposit} at {DateTime.Now.ToString()} Current Balance: ${omni.Bal}");
string omniWithdrawalPara = ($"Transaction: -${omni.Withdrawal} at {DateTime.Now.ToString()} Current Balance: ${omni.Bal}");
//INSTANTIATING STREAMWRITER FILES
// Everyday
using (StreamWriter everdayAccountStreamSummary = new StreamWriter("EverdaySummary.txt", true))
{
if (everyday.Deposit > 0)
{
everdayAccountStreamSummary.WriteLine(everydayDepositPara);
everyday.Deposit = 0;
}
if (everyday.Withdrawal > 0)
{
everdayAccountStreamSummary.WriteLine(everdayWithdrawalPara);
everyday.Withdrawal = 0;
}
}
//Investment
using (StreamWriter investmentAccountStreamSummary = new StreamWriter("InvestmentSummary.txt", true))
{
if (investment.Deposit > 0)
{
investmentAccountStreamSummary.WriteLine(investmentDepositPara);
investment.Deposit = 0;
}
if (investment.Withdrawal > 0)
{
investmentAccountStreamSummary.WriteLine(investmentWithdrawalPara);
investment.Withdrawal = 0;
}
}
//Omni
using (StreamWriter omniAccountStreamSummary = new StreamWriter("OmniSummary.txt", true))
{
if (omni.Deposit > 0)
{
omniAccountStreamSummary.WriteLine(omniDepositPara);
omni.Deposit = 0;
}
if (omni.Withdrawal > 0)
{
omniAccountStreamSummary.WriteLine(omniWithdrawalPara);
omni.Withdrawal = 0;
}
}
client.DisplayMenu();//the online banking menu
string userchoice = Console.ReadLine();//user input from menu options
switch (userchoice.ToUpper())
{
case "1": // Display Client Info
Console.Clear();
Console.WriteLine(client.ClientInfo());
break;
case "2A": // Display Everday Account Balance
Console.Clear();
everyday.Balance();
Console.WriteLine("Everyday Account Balance: $" + everyday.Bal);
break;
case "2B": // Display Investment Account Balance
Console.Clear();
investment.Balance();
Console.WriteLine("Investment Account Balance: $" + investment.Bal);
break;
case "2C": // Display Omni Account Balance
Console.Clear();
omni.Balance();
Console.WriteLine("Omni Account Balance: $" + omni.Bal);
break;
case "3A": // Everyday Account Deposit
Console.Clear();
Console.WriteLine("How much would you like to deposit?");
everyday.Deposit = double.Parse(Console.ReadLine());
Console.WriteLine("You deposited: $" + everyday.Deposit);
everyday.DepositBalance(everyday.Deposit);
break;
case "3B":
Console.Clear(); // Investment Account Deposit
Console.WriteLine("How much would you like to deposit?");
investment.Deposit = double.Parse(Console.ReadLine());
Console.WriteLine("You deposited: $" + investment.Deposit);
investment.DepositBalance(investment.Deposit);
break;
case "3C":
Console.Clear(); // Omni Account Deposit
Console.WriteLine("How much would you like to deposit?");
omni.Deposit = double.Parse(Console.ReadLine());
Console.WriteLine("You deposited: $" + omni.Deposit);
omni.DepositBalance(omni.Deposit);
break;
case "4A": // Everyday account Withdrawal
Console.Clear();
Console.WriteLine("How much would you like to withdraw?");
everyday.Withdrawal = double.Parse(Console.ReadLine());
Console.WriteLine("You withdrew: $" + everyday.Withdrawal);
everyday.WithBalance(everyday.Withdrawal);
break;
case "4B":
Console.Clear(); // Investment Account Withdrawal
Console.WriteLine("How much would you like to withdraw?");
investment.Withdrawal = double.Parse(Console.ReadLine());
Console.WriteLine("You withdrew: $" + investment.Withdrawal);
investment.WithBalance(investment.Withdrawal);
break;
case "4C":
Console.Clear(); // Omni Account Withdrawal
Console.WriteLine("How much would you like to withdraw?");
omni.Withdrawal = double.Parse(Console.ReadLine());
Console.WriteLine("You withdrew: $" + omni.Withdrawal);
omni.WithBalance(omni.Withdrawal);
break;
case "5":
Console.Clear(); // Everyday Details
Console.WriteLine("Everyday Banking Details");
everyday.Balance();
Console.WriteLine("Everyday Account Balance: $" + everyday.Bal);
break;
case "6":
Console.Clear(); // Investment Details
Console.WriteLine("Investment Banking Details");
everyday.Balance();
Console.WriteLine("Investment Account Balance: $" + investment.Bal); // Add Interest Rate and Fee
Console.WriteLine("Interest Rate: " + investment.InterestInvestment + "%");
Console.WriteLine("Fee: "
);
break;
case "7":
Console.Clear(); // Omni Details
Console.WriteLine("Omni Banking Details");
everyday.Balance();
Console.WriteLine("Omni Account Balance: $" + omni.Bal);
Console.WriteLine("Interest Rate: " + omni.InterestOmni + "%");
Console.WriteLine("Fee: ");
break;
case "8":
Console.Clear(); // Exit Banking
Console.WriteLine("You have chosen to exit the online banking. Thanks and come again!");
Environment.Exit(0);
break;
default: // catch all, breaks the loop
Console.Clear();
test = false;
break;
}
} while (!test);
}
}
I've done a refactor of your code - it was really quite difficult to understand what you were trying to do - so it's quite a large change. I have removed a lot of duplication, but I couldn't really complete everything because there was quite a bit missing in your code too.
I can't answer how to fix your one method in your code because the way that you were changing the state in your account classes was really difficult to follow.
In my refactoring I'm always computing the Balance like this:
public decimal Balance => this.Opening + this.Deposits - this.Withdrawals + this.Interest - this.Fees;
So now it's just a matter of getting the various components of the Balance right.
Here's how Withdraw now works to do that:
public (decimal Withdrawn, decimal Fee) Withdraw(decimal amount)
{
if (amount <= 0m)
{
throw new System.InvalidOperationException("Withdrawal amount must be positive");
}
decimal fee = 0;
if (amount > this.Overdraft)
{
amount = 0m;
fee = 10m;
}
else if (this.Balance < amount)
{
amount = this.Balance;
}
this.Withdrawals -= amount;
return (amount, fee);
}
If I've understood correctly, when you try to withdraw more that the Overdraft amount then you get a $10 fee and nothing is withdrawn. I've added a check to make sure you can't withdraw more than the balance.
Here's the rest of my refactoring. Let me know what you need to discuss:
class Program
{
public class Client
{
private string _firstName;
private string _lastName;
private string _phoneNumber;
private string _address;
public Client(string firstName, string lastName, string phoneNumber, string address)
{
_firstName = firstName;
_lastName = lastName;
_phoneNumber = phoneNumber;
_address = address;
}
public string ClientInfo =>
$"Account Holder: {_firstName} {_lastName} Phone Number: {_phoneNumber} Address: {_address}";
}
public abstract class Account
{
private Client _client;
public Account(Client client, int accountNumber, decimal opening)
{
_client = client;
this.AccountNumber = accountNumber;
this.Opening = opening;
}
public Account(Client client, decimal opening) : this(client, Account.GenerateAccountNumber(), opening)
{ }
public int AccountNumber { get; private set; }
public string AccountType => $"{this.GetType().Name} Account";
public abstract decimal Overdraft { get; protected set; }
public decimal Opening { get; protected set; }
public decimal Deposits { get; protected set; }
public decimal Withdrawals { get; protected set; }
public decimal Interest { get; protected set; }
public decimal Fees { get; protected set; }
public decimal InterestRate { get; protected set; } = 4m;
public decimal Balance => this.Opening + this.Deposits - this.Withdrawals + this.Interest - this.Fees;
private static Random _random = new Random();
public static int GenerateAccountNumber() => _random.Next(100000000, 1000000000);
public (decimal Withdrawn, decimal Fee) Withdraw(decimal amount)
{
if (amount <= 0m)
{
throw new System.InvalidOperationException("Withdrawal amount must be positive");
}
decimal fee = 0;
if (amount > this.Overdraft)
{
amount = 0m;
fee = 10m;
}
else if (this.Balance < amount)
{
amount = this.Balance;
}
this.Withdrawals += amount;
this.Fees += fee;
return (amount, fee);
}
public decimal Deposit(decimal amount)
{
if (amount <= 0m)
{
throw new System.InvalidOperationException("Deposit amount must be positive");
}
this.Deposits += amount;
return amount;
}
public IEnumerable<string> GetTransactions()
{
var now = DateTime.Now;
if (this.Deposits > 0m)
{
yield return $"Deposits: +${this.Deposits} at {now.ToString()} Current Balance: ${this.Balance}";
}
if (this.Withdrawals > 0m)
{
yield return $"Withdrawals: +${this.Withdrawals} at {now.ToString()} Current Balance: ${this.Balance}";
}
}
public string Summary => String.Join(Environment.NewLine, this.AccountType, _client.ClientInfo, "Account Number: " + this.AccountNumber);
}
public class Everyday : Account
{
public decimal MinBalance { get; private set; } = 0m;
public decimal MaxBalance { get; private set; } = 1000000000000m;
public override decimal Overdraft { get; protected set; } = 100m;
public Everyday(Client client, decimal opening) : base(client, opening)
{ }
public Everyday(Client client, int accountNumber, decimal opening) : base(client, accountNumber, opening)
{ }
}
public class Investment : Account
{
public decimal InvestmentFee { get; private set; } = 10m;
public override decimal Overdraft { get; protected set; } = 100m;
public Investment(Client client, decimal opening) : base(client, opening)
{ }
public Investment(Client client, int accountNumber, decimal opening) : base(client, accountNumber, opening)
{ }
}
class Omni : Account
{
public override decimal Overdraft { get; protected set; } = 1000m;
public Omni(Client client, decimal opening) : base(client, opening)
{ }
public Omni(Client client, int accountNumber, decimal opening) : base(client, accountNumber, opening)
{ }
}
private static void DisplayBalance(Account account)
{
Console.WriteLine($"{account.AccountType} Balance: {account.Balance:$#,##0.00}");
}
private static void DepositAmount(Account account)
{
Console.WriteLine("How much would you like to deposit?");
decimal deposited = account.Deposit(decimal.Parse(Console.ReadLine()));
Console.WriteLine($"You deposited: {deposited:$#,##0.00} into your {account.AccountType}");
}
private static void WithdrawAmount(Account account)
{
Console.WriteLine("How much would you like to withdraw?");
var result = account.Withdraw(decimal.Parse(Console.ReadLine()));
Console.WriteLine($"You withdrew: {result.Withdrawn:$#,##0.00}");
if (result.Fee != 0m)
{
Console.WriteLine($"With fee: {result.Fee:$#,##0.00}");
}
}
private static void DisplayDetails(Everyday account)
{
Console.WriteLine("Everyday Banking Details");
Console.WriteLine($"{account.AccountType} Balance: {account.Balance:$#,##0.00}");
}
private static void DisplayDetails(Investment account)
{
Console.WriteLine("Investment Banking Details");
Console.WriteLine($"{account.AccountType} Balance: {account.Balance:$#,##0.00}");
Console.WriteLine("Interest Rate: " + account.InterestRate + "%");
Console.WriteLine("Fee: ");
}
private static void DisplayDetails(Omni account)
{
Console.WriteLine("Omni Banking Details");
Console.WriteLine($"{account.AccountType} Balance: {account.Balance:$#,##0.00}");
Console.WriteLine("Interest Rate: " + account.InterestRate + "%");
Console.WriteLine("Fee: ");
}
private static void Main(string[] args)
{
bool test = false;
Client client = new Client("Tayla", "Brown", "027493922", "55 Grey Rd"); // Our one client
Everyday everyday = new Everyday(client, Account.GenerateAccountNumber(), 2000m);
Investment investment = new Investment(client, 500m);
Omni omni = new Omni(client, 1000m);
File.WriteAllText(#"EverydaySummary.txt", everyday.Summary);
File.WriteAllText(#"InvestmentSummary.txt", investment.Summary);
File.WriteAllText(#"OmniSummary.txt", omni.Summary);
do
{
File.WriteAllLines("EverdaySummary.txt", everyday.GetTransactions());
File.WriteAllLines("InvestmentSummary.txt", investment.GetTransactions());
File.WriteAllLines("OmniSummary.txt", omni.GetTransactions());
DisplayMenu();
string userchoice = Console.ReadLine();//user input from menu options
switch (userchoice.ToUpper())
{
case "1": // Display Client Info
//Console.Clear();
Console.WriteLine(client.ClientInfo);
break;
case "2A": // Display Everday Account Balance
//Console.Clear();
DisplayBalance(everyday);
break;
case "2B": // Display Investment Account Balance
//Console.Clear();
DisplayBalance(investment);
break;
case "2C": // Display Omni Account Balance
//Console.Clear();
DisplayBalance(omni);
break;
case "3A": // Everyday Account Deposit
//Console.Clear();
DepositAmount(everyday);
break;
case "3B":
//Console.Clear(); // Investment Account Deposit
DepositAmount(investment);
break;
case "3C":
//Console.Clear(); // Omni Account Deposit
DepositAmount(omni);
break;
case "4A": // Everyday account Withdrawal
//Console.Clear();
WithdrawAmount(everyday);
break;
case "4B":
//Console.Clear(); // Investment Account Withdrawal
WithdrawAmount(investment);
break;
case "4C":
//Console.Clear(); // Omni Account Withdrawal
WithdrawAmount(omni);
break;
case "5":
//Console.Clear(); // Everyday Details
DisplayDetails(everyday);
break;
case "6":
//Console.Clear(); // Investment Details
DisplayDetails(investment);
break;
case "7":
//Console.Clear(); // Omni Details
DisplayDetails(omni);
break;
case "8":
//Console.Clear(); // Exit Banking
Console.WriteLine("You have chosen to exit the online banking. Thanks and come again!");
test = true;
break;
default: // catch all, breaks the loop
//Console.Clear();
test = false;
break;
}
} while (!test);
}
//displays online banking menu
private static void DisplayMenu()
{
Console.WriteLine("Welcome to your online bank account\nPlease choose from the options below: ");
Console.WriteLine("");
Console.WriteLine("1.View Client Info");
Console.WriteLine("");
Console.WriteLine("2. View Account Balance:");
Console.WriteLine(" 2A.Everyday\n 2B.Investment\n 2C.Omni");
Console.WriteLine("");
Console.WriteLine("3.Deposit Funds:\n 3A.Everyday\n 3B.Investment\n 3C.Omni");
Console.WriteLine("");
Console.WriteLine("4.Withdraw Funds:\n 4A.Everyday\n 4B.Investment\n 4C.Omni");
Console.WriteLine("");
Console.WriteLine("5.View Everyday Banking Details");
Console.WriteLine("6.View Investment Banking Details");
Console.WriteLine("7.View Omni Banking details");
Console.WriteLine("");
Console.WriteLine("8.Exit");
}
}
Here's some test code that shows that this should be working now.
private static void Main(string[] args)
{
Client client = new Client("Tayla", "Brown", "027493922", "55 Grey Rd");
Everyday everyday = new Everyday(client, Account.GenerateAccountNumber(), 30m);
Console.WriteLine($"Balance: {everyday.Balance}");
var r1 = everyday.Withdraw(15m);
Console.WriteLine($"Withdrawn: {r1.Withdrawn}, Fee: {r1.Fee}, Balance: {everyday.Balance}");
var r2 = everyday.Withdraw(1000m);
Console.WriteLine($"Withdrawn: {r2.Withdrawn}, Fee: {r2.Fee}, Balance: {everyday.Balance}");
var r3 = everyday.Withdraw(10m);
Console.WriteLine($"Withdrawn: {r3.Withdrawn}, Fee: {r3.Fee}, Balance: {everyday.Balance}");
}
That gives:
Balance: 30
Withdrawn: 15, Fee: 0, Balance: 15
Withdrawn: 0, Fee: 10, Balance: 5
Withdrawn: 5, Fee: 0, Balance: 0
Here's a version with transactions.
class Program
{
public class Client
{
private string _firstName;
private string _lastName;
private string _phoneNumber;
private string _address;
public Client(string firstName, string lastName, string phoneNumber, string address)
{
_firstName = firstName;
_lastName = lastName;
_phoneNumber = phoneNumber;
_address = address;
}
public string ClientInfo =>
$"Account Holder: {_firstName} {_lastName} Phone Number: {_phoneNumber} Address: {_address}";
}
public abstract class Account
{
private Client _client;
public Account(Client client, int accountNumber, decimal opening)
{
_client = client;
this.AccountNumber = accountNumber;
this.Transactions.Add(Transaction.Create(DateTime.Now, opening, TransactionType.Opening));
}
public Account(Client client, decimal opening) : this(client, Account.GenerateAccountNumber(), opening)
{ }
public int AccountNumber { get; private set; }
public string AccountType => $"{this.GetType().Name} Account";
public abstract decimal Overdraft { get; protected set; }
public List<Transaction> Transactions { get; private set; } = new List<Transaction>();
public decimal InterestRate { get; protected set; } = 4m;
public decimal Balance => this.Transactions.Sum(t => t.Amount);
private static Random _random = new Random();
public static int GenerateAccountNumber() => _random.Next(100000000, 1000000000);
public (decimal Withdrawn, decimal Fee) Withdraw(decimal amount)
{
if (amount <= 0m)
{
throw new System.InvalidOperationException("Withdrawal amount must be positive");
}
decimal fee = 0;
if (amount > this.Overdraft)
{
amount = 0m;
fee = 10m;
}
else if (this.Balance < amount)
{
amount = this.Balance;
}
if (amount > 0m)
{
this.Transactions.Add(Transaction.Create(DateTime.Now, amount, TransactionType.Withdrawal));
}
if (fee > 0m)
{
this.Transactions.Add(Transaction.Create(DateTime.Now, fee, TransactionType.Fee));
}
return (amount, fee);
}
public decimal Deposit(decimal amount)
{
if (amount <= 0m)
{
throw new System.InvalidOperationException("Deposit amount must be positive");
}
this.Transactions.Add(Transaction.Create(DateTime.Now, amount, TransactionType.Deposit));
return amount;
}
public string Summary => String.Join(Environment.NewLine, this.AccountType, _client.ClientInfo, "Account Number: " + this.AccountNumber);
}
public class Everyday : Account
{
public decimal MinBalance { get; private set; } = 0m;
public decimal MaxBalance { get; private set; } = 1000000000000m;
public override decimal Overdraft { get; protected set; } = 100m;
public Everyday(Client client, decimal opening) : base(client, opening)
{ }
public Everyday(Client client, int accountNumber, decimal opening) : base(client, accountNumber, opening)
{ }
}
public class Investment : Account
{
public decimal InvestmentFee { get; private set; } = 10m;
public override decimal Overdraft { get; protected set; } = 100m;
public Investment(Client client, decimal opening) : base(client, opening)
{ }
public Investment(Client client, int accountNumber, decimal opening) : base(client, accountNumber, opening)
{ }
}
class Omni : Account
{
public override decimal Overdraft { get; protected set; } = 1000m;
public Omni(Client client, decimal opening) : base(client, opening)
{ }
public Omni(Client client, int accountNumber, decimal opening) : base(client, accountNumber, opening)
{ }
}
public class Transaction
{
public DateTime When { get; private set; }
public decimal Amount { get; private set; }
public TransactionType Type { get; private set; }
public static Transaction Create(DateTime when, decimal amount, TransactionType type)
{
if (amount <= 0m)
{
throw new System.InvalidOperationException("Transaction amount must be positive");
}
return new Transaction(when, (type == TransactionType.Withdrawal || type == TransactionType.Fee) ? -amount : amount, type);
}
private Transaction(DateTime when, decimal amount, TransactionType type)
{
this.When = when;
this.Amount = amount;
this.Type = type;
}
}
public enum TransactionType { Opening, Deposit, Withdrawal, Fee, Interest }
private static void DisplayBalance(Account account)
{
Console.WriteLine($"{account.AccountType} Balance: {account.Balance:$#,##0.00}");
}
private static void DepositAmount(Account account)
{
Console.WriteLine("How much would you like to deposit?");
decimal deposited = account.Deposit(decimal.Parse(Console.ReadLine()));
Console.WriteLine($"You deposited: {deposited:$#,##0.00} into your {account.AccountType}");
}
private static void WithdrawAmount(Account account)
{
Console.WriteLine("How much would you like to withdraw?");
var result = account.Withdraw(decimal.Parse(Console.ReadLine()));
Console.WriteLine($"You withdrew: {result.Withdrawn:$#,##0.00}");
if (result.Fee != 0m)
{
Console.WriteLine($"With fee: {result.Fee:$#,##0.00}");
}
}
private static void DisplayDetails(Everyday account)
{
Console.WriteLine("Everyday Banking Details");
Console.WriteLine($"{account.AccountType} Balance: {account.Balance:$#,##0.00}");
}
private static void DisplayDetails(Investment account)
{
Console.WriteLine("Investment Banking Details");
Console.WriteLine($"{account.AccountType} Balance: {account.Balance:$#,##0.00}");
Console.WriteLine("Interest Rate: " + account.InterestRate + "%");
Console.WriteLine("Fee: ");
}
private static void DisplayDetails(Omni account)
{
Console.WriteLine("Omni Banking Details");
Console.WriteLine($"{account.AccountType} Balance: {account.Balance:$#,##0.00}");
Console.WriteLine("Interest Rate: " + account.InterestRate + "%");
Console.WriteLine("Fee: ");
}
private static void Main(string[] args)
{
bool test = false;
Client client = new Client("Tayla", "Brown", "027493922", "55 Grey Rd"); // Our one client
Everyday everyday = new Everyday(client, Account.GenerateAccountNumber(), 2000m);
Investment investment = new Investment(client, 500m);
Omni omni = new Omni(client, 1000m);
File.WriteAllText(#"EverydaySummary.txt", everyday.Summary);
File.WriteAllText(#"InvestmentSummary.txt", investment.Summary);
File.WriteAllText(#"OmniSummary.txt", omni.Summary);
do
{
File.WriteAllLines("EverdaySummary.txt", everyday.Transactions.Select(t => $"{t.When} {t.Type} {t.Amount}"));
File.WriteAllLines("InvestmentSummary.txt", investment.Transactions.Select(t => $"{t.When} {t.Type} {t.Amount}"));
File.WriteAllLines("OmniSummary.txt", omni.Transactions.Select(t => $"{t.When} {t.Type} {t.Amount}"));
DisplayMenu();
string userchoice = Console.ReadLine();//user input from menu options
switch (userchoice.ToUpper())
{
case "1": // Display Client Info
//Console.Clear();
Console.WriteLine(client.ClientInfo);
break;
case "2A": // Display Everday Account Balance
//Console.Clear();
DisplayBalance(everyday);
break;
case "2B": // Display Investment Account Balance
//Console.Clear();
DisplayBalance(investment);
break;
case "2C": // Display Omni Account Balance
//Console.Clear();
DisplayBalance(omni);
break;
case "3A": // Everyday Account Deposit
//Console.Clear();
DepositAmount(everyday);
break;
case "3B":
//Console.Clear(); // Investment Account Deposit
DepositAmount(investment);
break;
case "3C":
//Console.Clear(); // Omni Account Deposit
DepositAmount(omni);
break;
case "4A": // Everyday account Withdrawal
//Console.Clear();
WithdrawAmount(everyday);
break;
case "4B":
//Console.Clear(); // Investment Account Withdrawal
WithdrawAmount(investment);
break;
case "4C":
//Console.Clear(); // Omni Account Withdrawal
WithdrawAmount(omni);
break;
case "5":
//Console.Clear(); // Everyday Details
DisplayDetails(everyday);
break;
case "6":
//Console.Clear(); // Investment Details
DisplayDetails(investment);
break;
case "7":
//Console.Clear(); // Omni Details
DisplayDetails(omni);
break;
case "8":
//Console.Clear(); // Exit Banking
Console.WriteLine("You have chosen to exit the online banking. Thanks and come again!");
test = true;
break;
default: // catch all, breaks the loop
//Console.Clear();
test = false;
break;
}
} while (!test);
}
//displays online banking menu
private static void DisplayMenu()
{
Console.WriteLine("Welcome to your online bank account\nPlease choose from the options below: ");
Console.WriteLine("");
Console.WriteLine("1.View Client Info");
Console.WriteLine("");
Console.WriteLine("2. View Account Balance:");
Console.WriteLine(" 2A.Everyday\n 2B.Investment\n 2C.Omni");
Console.WriteLine("");
Console.WriteLine("3.Deposit Funds:\n 3A.Everyday\n 3B.Investment\n 3C.Omni");
Console.WriteLine("");
Console.WriteLine("4.Withdraw Funds:\n 4A.Everyday\n 4B.Investment\n 4C.Omni");
Console.WriteLine("");
Console.WriteLine("5.View Everyday Banking Details");
Console.WriteLine("6.View Investment Banking Details");
Console.WriteLine("7.View Omni Banking details");
Console.WriteLine("");
Console.WriteLine("8.Exit");
}
}

How to create an array of class type objects?

I want to create an array of class type elements.
And it would be nice to enter this data from the keyboard, but I don’t know yet how, any Tips?
class Transportation
{
private string name; //name company
private double cost; //unit price
private double weight; // Shipping Weight
public Transportation(string name,double cost, double weight)
{
Name = name;
Cost = cost;
Weight = weight;
}
public Transportation()
{
Name = "none";
Cost = 0;
Weight = 0;
}
public double Cost { get => cost; set => cost = value; }
public string Name { get => name; set => name = value; }
public double Weight { get => weight; set => weight = value; }
}
class Program
{
static void Main(string[] args)
{
Transportation company = new Transportation("LG",24.05,1000);
}
}
Yuriy, sorry by my english.
If I understand correctly, you want to create an array of a class, in this case the Transportation class
This do the magic
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Transportation
{
private string name; //name company
private double cost; //unit price
private double weight; // Shipping Weight
public Transportation(string name, double cost, double weight)
{
Name = name;
Cost = cost;
Weight = weight;
}
public Transportation()
{
Name = "none";
Cost = 0;
Weight = 0;
}
public double Cost { get => cost; set => cost = value; }
public string Name { get => name; set => name = value; }
public double Weight { get => weight; set => weight = value; }
}
class Program
{
static void Main(string[] args)
{
Transportation[] company = GetTransportations();
foreach (Transportation item in company)
{
Console.WriteLine(item.Name + " => " + item.Cost + " => " + item.Weight);
}
Console.ReadKey();
}
public static Transportation[] GetTransportations()
{
string name = string.Empty; //name company
double cost = 0; //unit price
double weight = 0; // Shipping Weight
Transportation[] transportations = new Transportation[] { };
List<Transportation> transportationsList = new List<Transportation>();
while (true)
{
while (true)
{
Console.WriteLine("Insert the name of product: ");
name = Console.ReadLine();
if (!string.IsNullOrEmpty(name))
{
break;
}
}
while (true)
{
Console.WriteLine("Insert the cost of product: ");
string costString = Console.ReadLine();
if (double.TryParse(costString, out double c))
{
cost = c;
break;
}
}
while (true)
{
Console.WriteLine("Insert the weight of product: ");
string Sweight = Console.ReadLine();
if (double.TryParse(Sweight, out double w))
{
weight = w;
break;
}
}
transportationsList.Add(new Transportation(name, cost, weight));
Console.WriteLine("Continue to add products? Y/N: ");
string continueToAdd = Console.ReadLine();
if (continueToAdd.Substring(0, 1).ToUpper() == "N")
{
return transportationsList.ToArray();
}
}
}
}
}

containing type does not implement interface 'System.IComparable' error

namespace Theprogram.cs
{
class Program
{
static void Main(string[] args)
{
CreditCustomer[] creditCustomer = new CreditCustomer[5];
int x, y;
bool goodNum;
for (x = 0; x < creditCustomer.Length; ++x)
{
creditCustomer[x] = new CreditCustomer();
Console.Write("Enter customer number ");
creditCustomer[x].CustomerNumber = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y < x; ++y)
{
if (creditCustomer[x].Equals(creditCustomer[y]))
goodNum = false;
}
while (!goodNum)
{
Console.Write("Sorry, the customer number " +
creditCustomer[x].CustomerNumber + " is a duplicate. " +
"\nPlease reenter ");
creditCustomer[x].CustomerNumber = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y < x; ++y)
{
if (creditCustomer[x].Equals(creditCustomer[y]))
goodNum = false;
}
}
Console.Write("Enter name ");
creditCustomer[x].CustomerName = Console.ReadLine();
Console.Write("Enter age ");
creditCustomer[x].Rate = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter amount due ");
creditCustomer[x].AmountDue = Convert.ToDouble(Console.ReadLine());
}
Array.Sort(creditCustomer);
Array.Sort(customer);
}
}
class Customer : IComparable<Customer>
{
private int customerNumber;
public int CustomerNumber
{
get
{
return customerNumber;
}
set
{
customerNumber = value;
}
}
private string customerName;
public string CustomerName
{
get
{
return customerName;
}
set
{
customerName = value;
}
}
private double amountDue;
public double AmountDue
{
get
{
return amountDue;
}
set
{
amountDue = value;
}
}
public Customer(int num, string name, int amt)
{
CustomerNumber = num;
CustomerName = name;
AmountDue = amt;
}
public Customer(): this(9, "ZZZ", 0)
{
}
public override bool Equals(Object e)
{
bool equal;
Customer temp = (Customer)e;
if (this.CustomerNumber == temp.CustomerNumber)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return CustomerNumber;
}
public override string ToString()
{
return (GetType() + " Credit Customer " + CustomerNumber + " " + CustomerName +
" Amount Due is " + AmountDue.ToString("C") + " Interest rate is ");
}
protected virtual int IComparable.CompareTo(Object o)
{
int returnVal;
Customer temp = (Customer)o;
if (this.CustomerNumber >
temp.CustomerNumber)
returnVal = 1;
else
if (this.CustomerNumber < temp.CustomerNumber)
returnVal = -1;
else
returnVal = 0;
return returnVal;
}
}
class CreditCustomer : Customer, IComparable<CreditCustomer>
{
public int Rate {get; set;}
int MonthlyPayment { get; set; }
public CreditCustomer(int customerNumber, string customerName, int amountDue, int Rate) : base(customerNumber, customerName, amountDue)
{ }
public CreditCustomer(): this(0, "", 0, 0)
{ }
public override string ToString()
{
return (GetType() + " Credit Customer " + CustomerNumber + " " + CustomerName +
" Amount Due is " + AmountDue.ToString("C") + " Interest rate is " + Rate + " Monthly Payment is " + MonthlyPayment);
}
int IComparable.CompareTo(object o)
{
int returnVal;
CreditCustomer temp = (CreditCustomer)o;
if (this.CustomerNumber > temp.CustomerNumber)
returnVal = 1;
else
if (this.CustomerNumber < temp.CustomerNumber)
returnVal = -1;
else
returnVal = 0;
return returnVal;
}
}
}
I am having trouble implementing Icomparable in C# for my parent and child classes as I get the error:
does not implement interface member'System.IComparable.CompareTo
I really need help on how to implement the Icomparable interface so that I can use the compareTo method on my array of object. Any help would be greatly appreciated.
If you're using Visual Studio and are not sure how to implement an interface, just right click IComparable in the class declaration
class CreditCustomer : Customer, IComparable<CreditCustomer>
and select Implement Interface and any of the two options.
The correct signature for the implementation in CreditCustomer would be either:
public int CompareTo(CreditCustomer other)
{
}
or
int IComparable<CreditCustomer>.CompareTo(CreditCustomer other)
{
}
Note that the second signature would hide the method unless you cast the object to IComparable<CreditCustomer>.
As SLaks mentioned in his comment, there are, in fact, two different interfaces that are named IComparable which can be easily confused:
IComparable is an older, non-generic interface which allows comparison between an object and any other object. There's no type checking - your CreditCustomer can be compared to an int or a List<string> or anything. This interface defines a single method, CompareTo(object obj). This is the method you have in your class.
IComparable<T> is a newer, generic interface. It's very similar to IComparable, but enforces type checking - it only compares T to T, so you don't have to write a lot of boilerplate code making sure that someone didn't try to compare your CreditCustomer to a Dog or something. It also defines a single method - CompareTo(T obj). This is the interface that you marked your class as implementing.
Despite being similarly named, these two are, as far as the compiler is concerned, two different interfaces. If you don't have a CompareTo method that accepts a CreditCustomer argument, you're not implementing IComparable<CreditCustomer>, and that's why it's giving you an error. Either change your method signature to match the interface, or change the interface you're using to one that matches the method signature. Probably the former.

Comparing user input to previously entered values

I am having a problem getting my program to check the input previous and compare it so the user cannot duplicate an order number. Right now the program will run all the way through and look the way I want, but it accepts duplicate order numbers while I would like it to inform the user and ask them to reenter. The problem seems to be that my check[y] array does not contain any value when I compare it. How do I get this array to contain the previously entered order numbers so it will display the error message. I am just going to post the entire code so you can see what I have done so far. Others have suggested the List type, but I am a student and have not learned this yet. I believe I am supposed to use the Equals method. Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assignment6_Hergott
{
class Order : IComparable <Order>
{
public int orderNumber { get; set; }
public string customerName { get; set; }
public int quanityOrdered { get; set; }
public double total;
public const double priceEach = 19.95;
public Order()
{
}
public Order(int number, string name, int quanity)
{
number = orderNumber;
name = customerName;
quanity = quanityOrdered;
}
public double totalPrice
{
get
{
return total;
}
}
public int CompareTo(Order o)
{
return this.orderNumber.CompareTo(o.orderNumber);
}
public override bool Equals(Object e)
{
bool equal;
Order temp = (Order)e;
if (orderNumber == temp.orderNumber)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return Convert.ToInt32(orderNumber);
}
public override string ToString()
{
return "ShippedOrder " + orderNumber + " " + customerName + " " + quanityOrdered +
" # " + priceEach + " each.";
}
}
class ShippedOrder : Order
{
public const int shippingFee = 4;
public override string ToString()
{
return base.ToString() + " Shipping is " + shippingFee + " Total is " + totalPrice;
}
}
class Program
{
static void Main(string[] args)
{
double sum = 0;
ShippedOrder[] orderArray = new ShippedOrder[5];
ShippedOrder[] check = new ShippedOrder[5];
bool wrong = true;
for (int x = 0; x < orderArray.Length; ++x)
{
orderArray[x] = new ShippedOrder();
Console.Write("Enter order number: ");
orderArray[x].orderNumber = Convert.ToInt32(Console.ReadLine());
for (int y = 0; y < x; y++)
{
check[y] = new ShippedOrder();
if (orderArray[x].Equals(check[y]))
wrong = false;
while (!wrong)
{
Console.WriteLine("Sorry, the order number {0} is a duplicate.
\nPlease reenter: ", orderArray[x].orderNumber);
for (y = 0; y < x; y++)
{
if (orderArray[x].Equals(check[y]))
wrong = false;
}
check[y] = orderArray[x];
}
}
Console.Write("Enter cusomer name: ");
orderArray[x].customerName = Console.ReadLine();
Console.Write("Enter quanity: ");
orderArray[x].quanityOrdered = Convert.ToInt32(Console.ReadLine());
orderArray[x].total = orderArray[x].quanityOrdered * Order.priceEach +
ShippedOrder.shippingFee;
sum += orderArray[x].total;
}
Array.Sort(orderArray);
for (int x = 0; x < orderArray.Length; x++)
{
Console.WriteLine(orderArray[x].ToString());
}
Console.WriteLine();
Console.WriteLine("Total for all orders is {0:c} ", sum);
}
}
}
I had a few minutes so I changed my answer to show you one way it could be done. If you just copy/paste this you'll be doing yourself a disservice, though (and your instructor will probably be able to tell). Take a look at the solution and see how it differs from yours. I hesitated to post a full solution but I thought this might be an okay way for you to figure out what you'd done wrong.
namespace ConsoleApplication2
{
using System;
using System.Linq;
public class Order : IComparable<Order>
{
public const double PriceEach = 19.95;
public Order()
{
}
public Order(int number, string name, int quanity)
{
this.OrderNumber = number;
this.CustomerName = name;
this.QuanityOrdered = quanity;
}
public int OrderNumber { get; set; }
public string CustomerName { get; set; }
public int QuanityOrdered { get; set; }
public int CompareTo(Order o)
{
return this.OrderNumber.CompareTo(o.OrderNumber);
}
public override bool Equals(object e)
{
int compareTo;
int.TryParse(e.ToString(), out compareTo);
return this.OrderNumber == compareTo;
}
public override int GetHashCode()
{
return Convert.ToInt32(this.OrderNumber);
}
public override string ToString()
{
return "Shipped order number " + this.OrderNumber + " for customer " + this.CustomerName + " " + this.QuanityOrdered +
" # $" + PriceEach + " each.";
}
}
public class ShippedOrder : Order
{
public const int ShippingFee = 4;
public double TotalPrice
{
get
{
return (this.QuanityOrdered * PriceEach) + ShippingFee;
}
}
public override string ToString()
{
return base.ToString() + " Shipping is $" + ShippingFee + ". Total is $" + this.TotalPrice;
}
}
public class Program
{
private static readonly int[] OrderNumbers = new int[5];
private static readonly ShippedOrder[] ShippedOrders = new ShippedOrder[5];
public static void Main(string[] args)
{
double sum = 0;
for (var i = 0; i < OrderNumbers.Length; i++)
{
OrderNumbers[i] = InputOrderNumber();
var name = InputCustomerName();
var quantity = InputQuantity();
ShippedOrders[i] = new ShippedOrder { CustomerName = name, QuanityOrdered = quantity, OrderNumber = OrderNumbers[i] };
sum += ShippedOrders[i].TotalPrice;
}
Array.Sort(ShippedOrders);
foreach (var t in ShippedOrders)
{
Console.WriteLine(t.ToString());
}
Console.WriteLine();
Console.WriteLine("Total for all orders is {0:c} ", sum);
Console.WriteLine();
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
private static int InputOrderNumber()
{
Console.Write("Enter order number: ");
var parsedOrderNumber = InputNumber();
if (ShippedOrders.Any(shippedOrder => shippedOrder != null && shippedOrder.OrderNumber.Equals(parsedOrderNumber)))
{
Console.WriteLine("Order number {0} is a duplicate.", parsedOrderNumber);
return InputOrderNumber();
}
return parsedOrderNumber;
}
private static string InputCustomerName()
{
Console.Write("Enter customer name: ");
var customerName = Console.ReadLine();
if (customerName == null || string.IsNullOrEmpty(customerName.Trim()))
{
Console.WriteLine("Customer name may not be blank.");
return InputCustomerName();
}
return customerName;
}
private static int InputQuantity()
{
Console.Write("Enter quantity: ");
return InputNumber();
}
private static int InputNumber()
{
int parsedInput;
var input = Console.ReadLine();
if (!int.TryParse(input, out parsedInput))
{
Console.WriteLine("Enter a valid number.");
return InputNumber();
}
return parsedInput;
}
}
}
my check[y] array does not contain any value when I compare it. How do
I get this array to contain the previously entered order numbers
If you want check[] to contain order numbers, it needs to be of the type of order number (an int, in this case). So whenever you add a new order to the orderArray, also add its number to the check array. Then you can test against earlier numbers.
If this doesn't solve your problem, add a follow-up question as a comment telling us what you tried and we can go from there.

Categories

Resources