First and foremost, I feel it necessary to mention that I am currently using replit for this program. The issue that I am currently having with my code is that it runs perfectly, the only issue is that when I try to backspace using the methods listed below and fix a number or letter that I have mistyped in my input while running the program, I get an error saying that the value must be positive and below the buffer height. I realized that the issue is some of my Console.ReadLine(); placements. They are causing my program to read backspace as an input and in turn, I am receiving an error because backspace is neither a letter or number input. Is there any way that I can move them around without having to rewrite the whole method line?
public static void AddItemToStore() {
Console.WriteLine("========= Adding Item to Store =========");
Console.WriteLine();
Console.WriteLine("You will need to enter an item description, price, and quantity on hand.");
Console.WriteLine();
Console.WriteLine("Please enter an item description:");
string input = Console.ReadLine();
double entry = GetPrice();
int value = GetQuantity();
itemDescription.Add(input);
itemPrice.Add(Convert.ToDouble(entry));
itemQoh.Add(value);
SaveData();
}
public static string GetCustomerName() {
Console.WriteLine();
Console.WriteLine("=========== List of Customers =========== ");
Console.WriteLine();
for (int i = 0; i < salesCustomerName.Count; i++) {
Console.WriteLine($"{i + 1}. {salesCustomerName[i]} ");
Console.WriteLine();
}
while (true) {
Console.WriteLine("Please choose a Customer name:");
Console.WriteLine();
return Console.ReadLine();
}
}
public static double GetPrice() {
while (true) {
Console.WriteLine();
Console.WriteLine("Enter the price of the item (x.xx):");
string entry = Console.ReadLine();
double value;
if (!double.TryParse(entry, out value) || value <= 0){
Console.WriteLine("Please enter a valid price value.");
} else {
return Convert.ToDouble(entry);
}
}
}
public static int GetQuantity() {
while (true){
Console.WriteLine();
Console.WriteLine("Please enter the item quantity:");
string entry = Console.ReadLine();
int value = 0;
if (Int32.TryParse(entry, out value) && Convert.ToInt32(entry) > 0){
return Convert.ToInt32(entry);
}
else{
Console.WriteLine("Please enter a valid value.");
}
}
}
Listed above are the methods that I am currently having an issue with. They work perfectly with inputting information but as soon as I press backspace, I get an error. Down below I will have my whole program listed as well.
using System;
using System.Collections.Generic;
using System.IO;
class Program {
public static List<string> itemDescription = new List<string>();
public static List<double> itemPrice = new List<double>();
public static List<int> itemQoh = new List<int>();
public static List<string> customerName = new List<string>();
public static List<string> salesCustomerName = new List<string>();
public static List<string> salesItemDescription = new List<string>();
public static List<double> salesItemPrice = new List<double>();
public static List<int> salesQuantity = new List<int>();
public static void Main (string[] args) {
ReadData();
bool keepGoing = true;
while (keepGoing) {
string entry = GetMenuOption();
if (entry.ToLower() == "q"){
Console.WriteLine("Thanks for shopping with us! Come back soon! :)");
}
switch (entry) {
case "1":
GoShopping();
break;
case "2":
Management();
break;
case "Q":
keepGoing = false;
break;
}
}
}
public static void AddItemToStore() {
Console.WriteLine("========= Adding Item to Store =========");
Console.WriteLine();
Console.WriteLine("You will need to enter an item description, price, and quantity on hand.");
Console.WriteLine();
Console.WriteLine("Please enter an item description:");
string input = Console.ReadLine();
double entry = GetPrice();
int value = GetQuantity();
itemDescription.Add(input);
itemPrice.Add(Convert.ToDouble(entry));
itemQoh.Add(value);
SaveData();
}
public static void AddItemToCart(string name, int item) {
Console.WriteLine();
Console.WriteLine($"There are {itemQoh[item]} {itemDescription[item]} available for {itemPrice[item]:C2} each.");
Console.WriteLine();
Console.WriteLine("Please choose the amount of items that you would like to purchase");
string val = Console.ReadLine();
int pur_qty =0;
int num = -1;
if (!int.TryParse(val, out num)) {
Console.WriteLine("Please enter a valid integer");
} else {
pur_qty = Convert.ToInt32(val);
if (pur_qty <= itemQoh[item] ){
itemQoh[item] = itemQoh[item]-pur_qty;
salesCustomerName.Add(name);
salesItemDescription.Add(itemDescription[item]);
salesItemPrice.Add(itemPrice[item]);
salesQuantity.Add(pur_qty);
SaveData();
}else{
Console.WriteLine();
Console.WriteLine("Please enter a valid value");
}
}
}
public static void ChangePrice() {
Console.WriteLine("========= Changing Price =========");
int entry = Convert.ToInt32(GetItemNumber());
int price = 0;
Console.WriteLine();
Console.WriteLine($"Updating price. {itemDescription[price]} currently costs {itemPrice[price]:C2}.");
double new_price = GetPrice();
itemPrice[entry]= new_price;
SaveItems();
SaveData();
}
public static void ChangeQoh() {
Console.WriteLine("========= Changing Quantity =========");
int entry = Convert.ToInt32(GetItemNumber());
int value = 0;
Console.WriteLine($"Updating quantity. There are currently {itemQoh[value]} {itemDescription[value]} available.");
Console.WriteLine();
int new_qty = GetQuantity();
itemQoh[entry]=new_qty;
SaveItems();
SaveData();
}
public static string GetCustomerName() {
Console.WriteLine();
Console.WriteLine("=========== List of Customers =========== ");
Console.WriteLine();
for (int i = 0; i < salesCustomerName.Count; i++) {
Console.WriteLine($"{i + 1}. {salesCustomerName[i]} ");
Console.WriteLine();
}
while (true) {
Console.WriteLine("Please choose a Customer name:");
Console.WriteLine();
return Console.ReadLine();
}
}
public static int GetItemNumber() {
ListAllItems();
int counter = itemDescription.Count;
string number;
int item = 1;
bool keepGoing = true;
while (keepGoing){
Console.WriteLine("Please enter an item number:");
number = Console.ReadLine();
item = Convert.ToInt32(number);
if (item < 1 || item > counter) {
Console.WriteLine();
Console.WriteLine($"Please enter a valid item number between 1 and {counter}.");
Console.WriteLine();
} else {
keepGoing = false;
}
}
return item -1;
}
public static string GetMenuOption() {
Console.WriteLine("=========== Main Menu ===========");
Console.WriteLine("1. Go Shopping");
Console.WriteLine("2. Management Menu");
Console.WriteLine("Q. Quit the program");
Console.WriteLine();
Console.Write("Please enter your choice: ");
return Console.ReadLine();
}
public static string GetManagementMenuOption() {
Console.WriteLine();
Console.WriteLine("=========== Management Menu =====");
Console.WriteLine("1. Browse sales receipts");
Console.WriteLine("2. View all items");
Console.WriteLine("3. Add an item");
Console.WriteLine("4. Change Quantity of Items on Hand");
Console.WriteLine("5. Change Prices of Items");
Console.WriteLine("Q. Return to Main Menu");
Console.WriteLine();
Console.Write("Please enter your choice: ");
return Console.ReadLine();
}
public static double GetPrice() {
while (true) {
Console.WriteLine();
Console.WriteLine("Enter the price of the item (x.xx):");
string entry = Console.ReadLine();
double value;
if (!double.TryParse(entry, out value) || value <= 0){
Console.WriteLine("Please enter a valid price value.");
} else {
return Convert.ToDouble(entry);
}
}
}
public static string GetShoppingOption() {
Console.WriteLine();
Console.WriteLine("=========== Shopping Menu ===========");
Console.WriteLine("1. Choose an item");
Console.WriteLine("Q. Checkout");
Console.WriteLine();
Console.Write("Please enter your choice: ");
return Console.ReadLine();
}
public static int GetQuantity() {
while (true){
Console.WriteLine();
Console.WriteLine("Please enter the item quantity:");
string entry = Console.ReadLine();
int value = 0;
if (Int32.TryParse(entry, out value) && Convert.ToInt32(entry) > 0){
return Convert.ToInt32(entry);
}
else{
Console.WriteLine("Please enter a valid value.");
}
}
}
private static void GoShopping() {
Console.WriteLine();
Console.WriteLine("Please enter the name of the shopper:");
while (true) {
string name = Console.ReadLine();
string entry = GetShoppingOption();
switch (entry) {
case "1" :
int item = GetItemNumber();
if (item != -1) {
AddItemToCart(name, item);
SaveData();
}
break;
case "Q" :
PrintTotalCart(name);
return;
}
}
}
public static void ListAllItems() {
Console.WriteLine();
Console.WriteLine("============== All Items ============= ");
for (int i = 0; i < itemDescription.Count; i++) {
Console.WriteLine($"{i + 1}. {itemDescription[i]} costs {itemPrice[i]:C2}. There are {itemQoh[i]} available.");
Console.WriteLine();
}
}
public static void Management() {
while (true) {
string entry = GetManagementMenuOption();
if (entry.ToLower() == "q") {
return;
} else {
switch (entry) {
case "1" :
string customer = GetCustomerName();
PrintTotalCart(customer);
break;
case "2" :
ListAllItems();
break;
case "3" :
AddItemToStore();
break;
case "4" :
ChangeQoh();
break;
case "5" :
ChangePrice();
break;
default:
Console.WriteLine("Please make a valid selection");
break;
}
}
}
}
public static void PrintTotalCart(string name) {
Console.WriteLine();
Console.WriteLine($"======= All Purchases for {name} =======" );
double total_cost= 0;
for (int i = 0; i < salesCustomerName.Count; i++) {
if(salesCustomerName[i] == name) {
total_cost += salesQuantity[i] *salesItemPrice[i];
Console.WriteLine($"{salesQuantity[i]} {salesItemDescription[i]} at the price of {salesItemPrice[i]:C2} each for a total of {salesQuantity[i] *salesItemPrice[i]:C2}.");
}
}
Console.WriteLine();
Console.WriteLine($"Total cost of the cart for {name} is {total_cost:C2}.");
}
public static void ReadData() {
ReadItems();
ReadSales();
}
public static void ReadItems() {
var filename = "items.csv";
if (File.Exists(filename)) {
using (var reader = new StreamReader(filename)) {
reader.ReadLine();
while (!reader.EndOfStream) {
var line = reader.ReadLine();
var values = line.Split(",");
itemDescription.Add(values[0]);
itemPrice.Add(Convert.ToDouble(values[1]));
itemQoh.Add(Convert.ToInt32(values[2]));
}
}
}else {
Console.WriteLine($"{filename} not found");
}
}
public static void ReadSales() {
var filename = "sales.csv";
if (File.Exists(filename)) {
using (var reader = new StreamReader(filename)) {
reader.ReadLine();
while (!reader.EndOfStream) {
var line = reader.ReadLine();
var values = line.Split(",");
salesCustomerName.Add(values[0]);
salesItemDescription.Add(values[1]);
salesItemPrice.Add(Convert.ToDouble(values[2]));
salesQuantity.Add(Convert.ToInt32(values[3]));
}
}
}else {
Console.WriteLine($"{filename} not found");
}
}
public static void SaveData() {
SaveItems();
SaveSales();
}
public static void SaveItems() {
string filename = "items.csv";
using (var writer = new StreamWriter(filename)) {
writer.WriteLine("Item_Description,Item_Price,Qoh");
for (int i = 0; i < itemDescription.Count; i++) {
writer.WriteLine($"{itemDescription[i]},{itemPrice[i]},{itemQoh[i]}");
}
}
}
public static void SaveSales() {
string filename = "sales.csv";
using (var writer = new StreamWriter(filename)) {
writer.WriteLine("Customer_Name,Item_Description,Item_Price,Sales_Qty");
for (int i = 0; i < salesCustomerName.Count; i++) {
writer.WriteLine($"{salesCustomerName[i]},{salesItemDescription[i]},{salesItemPrice[i]},{salesQuantity[i]}");
}
}
}
}
This is the error that I receive each time that I enter the backspace.
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;
}
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");
}
}
i have a menu.Basically, i need to fix this error. I had it working fine, until now. With the Console.Clear on, I can ONLY use 1 or 8. 2-7 just clears out.It SHOULD display "You need to create a student first". If I turn Console.Clear off, then it works. However, I need it on since that is the part that resets the menu. Plus it also runs the line that is only supposed to run when you exit. I didn't change anything major.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GradeCalculator
{
class Program
{
static void Main(string[] args)
{
Student currentStudent = null;
bool running = true; // Logic 1
string input = "";
while(running)
{
// display menu
Console.Clear();
Console.WriteLine("Main menu: ");
Console.WriteLine("1. Create a student");
Console.WriteLine("2. Add a course to the current student");
Console.WriteLine("3. Remove a course from the current student");
Console.WriteLine("4. Add grades for a course");
Console.WriteLine("5. Display student info");
Console.WriteLine("6. Display grades for a course");
Console.WriteLine("7. Display all grades");
Console.WriteLine("8. Exit");
Console.Write("Enter a selection: (1 - 8): ");
input = Console.ReadLine().ToLower();
Console.WriteLine();
// handle choices
//------------------------------------------------------------------------
switch(input)
{
case "1":
case "create a student":
{
Console.Write("What is the students first name? ");
string firstName = Console.ReadLine();
Console.Write("What is the students last name? ");
string lastName = Console.ReadLine();
currentStudent = new Student(firstName, lastName);
Console.Write("How old is the student? ");
string studentAge = Console.ReadLine(); // Logic 2
int age;
while(!int.TryParse(studentAge, out age))
{
Console.Write("Please enter a number: ");
studentAge = Console.ReadLine();
}
currentStudent.Age = age;
Console.Write("What is the students address? ");
currentStudent.Address = Console.ReadLine();
Console.Write("What is the students email? ");
currentStudent.Email = Console.ReadLine();
Console.Write("What is the students phone number? ");
currentStudent.Phone = Console.ReadLine();
}
break;
case "2":
case "add a course to the current student":
{
if(currentStudent != null)
{
currentStudent.AddACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "3":
case "remove a course from the current student":
{
if (currentStudent != null)
{
currentStudent.RemoveACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "4":
case "add grades for a course":
{
if (currentStudent != null)
{
currentStudent.AddGradesForACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "5":
case "display student info":
{
if (currentStudent != null)
{
currentStudent.DisplayInfo();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "6":
case "display grades for a course":
{
if (currentStudent != null)
{
currentStudent.DisplayGradesForACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "7":
case "display all grades":
{
if (currentStudent != null)
{
currentStudent.DisplayAllGrades();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "8":
case "exit":
{
running = false; // Logic 6
}
break;
default:
return;
}
Console.WriteLine("You have chosen to exit");
//Console.ReadKey();
}
}
}
}
Student Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GradeCalculator
{
class Student
{
static int _nextStudentIDNum = 1000;
string _firstName;
string _lastName;
string _email;
string _address;
string _phoneNumber;
int _age;
int _studentIdNum;
List<Course> _courses;
public Student(string firstName, string lastName)
{
_firstName = firstName;
_lastName = lastName;
_studentIdNum = ++_nextStudentIDNum;
_courses = new List<Course>();
}
public string Name
{
get
{
return $"{_lastName}, {_firstName}";
}
}
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
public string Address
{
get
{
return _address;
}
set
{
_address = value;
}
}
public string Email
{
get
{
return _email;
}
set
{
_email = value;
}
}
public string Phone
{
get
{
return _phoneNumber;
}
set
{
_phoneNumber = value;
}
}
public int Age
{
get
{
return _age;
}
set
{
_age = value;
}
}
public int StudentNumber
{
get
{
return _studentIdNum;
}
set
{
_studentIdNum = value;
}
}
public List<Course> Courses
{
get
{
return _courses;
}
}
private int SelectCourse(string message)
{
int len = _courses.Count;
int index = -1;
if (len > 0) //Logic 3
{
for (index = 0; index < len; ++index)
{
Console.WriteLine($"{index + 1}. {_courses[index].Title}");
}
Console.Write(message);
string selection = Console.ReadLine();
while (!int.TryParse(selection, out index) || (index < 1 || index > len))
{
Console.Write("Please make a valid selection: ");
selection = Console.ReadLine();
}
--index;
}
return index;
}
public void AddACourse()
{
string input;
Console.Write("How many assignments are in the course? ");
input = Console.ReadLine();
int numAssignments = 0;
while (!int.TryParse(input, out numAssignments))
{
Console.Write("Please enter a number: ");
input = Console.ReadLine();
}
Course course = new Course(numAssignments);
Console.Write("What is the courses title? ");
course.Title = Console.ReadLine();
Console.Write("What is the courses description? ");
course.Description = Console.ReadLine();
_courses.Add(course);
}
public void RemoveACourse()
{
int index = SelectCourse("Select a course to remove. (Enter the number): ");
if (index == -1) //Logic 8
{
Console.WriteLine("No courses to remove. Try adding one first.");
}
else
{
_courses.RemoveAt(index);
}
}
public void AddGradesForACourse()
{
int index = SelectCourse("Select a course to add grades for. (Enter the number): ");
if (index == -1)
{
Console.WriteLine("No course to add grades to. Try adding one first.");
}
else
{
_courses[index].AddGrades();
}
}
public void DisplayGradesForACourse()
{
int index = SelectCourse("Select a course to display grades for. (Enter the number): ");
if (index == -1)
{
Console.WriteLine("No course to display grades for. Try adding one first.");
}
else
{
_courses[index].DisplayGrades();
}
}
public void DisplayAllGrades()
{
foreach (Course c in _courses)
{
c.DisplayGrades(); //Logic 7
}
}
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}\nAge: {Age}\nAddress: {Address}\nPhone: {Phone}\nEmail: {Email}");
}
}
}
Course Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GradeCalculator
{
class Course
{
string _title;
string _description;
Grade[] _grades;
int _graded;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
}
}
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
public Grade[] Grades
{
get
{
return _grades;
}
}
public Course(int numberOfAssignments)
{
_grades = new Grade[numberOfAssignments];
_graded = 32;
}
public void AddGrades()
{
do
{
for (int i = 0; i < _grades.Length; ++i)
{
_grades[i] = new Grade();
Console.Write($"Enter a description for assignment {i + 1}: ");
_grades[i].Description = Console.ReadLine();
string input;
float value;
Console.Write($"Enter the grade earned for assignment {i + 1} as a percentage (0 - 100): ");
input = Console.ReadLine();
while (!float.TryParse(input, out value)) // Logic 4
{
Console.WriteLine("Please enter a number: ");
input = Console.ReadLine();
}
_grades[i].PercentEarned = value;
Console.Write($"Enter assignment {i + 1}'s weight of total grade as a percentage (0 - 100): ");
input = Console.ReadLine();
while (!float.TryParse(input, out value))
{
Console.WriteLine("Please enter a number: ");
input = Console.ReadLine();
}
_grades[i].Weight = value;
}
}
while (ValidateWeightTotal() == false);
_graded = 0;
}
private bool ValidateWeightTotal()
{
float precisionFactor = 0.001f;
float _totalWeight = 0;
bool result = false;
for (int i = 0; i < _grades.Length; ++i)
{
_totalWeight += _grades[i].Weight;
}
if(_totalWeight < 100 + precisionFactor && _totalWeight > 100 - precisionFactor)
{
result = true;
}
if (result == false)
{
Console.WriteLine($"Weight total = {_totalWeight} instead of 100.\nPlease enter the values again.\n");
}
return result;
}
public float GetFinalGrade()
{
bool weightsAreValid = ValidateWeightTotal();
float finalGrade = 0;
if(weightsAreValid)
{
for (int i = 0; i < _grades.Length; ++i)
{
finalGrade += _grades[i].GetPercentOfFinalGrade();
}
}
return finalGrade;
}
public void DisplayGrades()
{
if (_graded == 0)
{
float total = 0f;
Console.WriteLine("-------------------------------------");
Console.WriteLine($"Title: {Title}");
for (int i = 0; i < _grades.Length; ++i)
{
Grade grade = _grades[i];
total += grade.GetPercentOfFinalGrade();
Console.WriteLine($"Desc: {grade.Description}\nEarned: {grade.PercentEarned}\nPercent towards final grade: {grade.GetPercentOfFinalGrade()}\n");
}
Console.WriteLine($"Grade for the course: {total}");
Console.WriteLine("-------------------------------------");
}
else
{
Console.WriteLine("Please add grades first.");
}
}
}
}
Grade Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GradeCalculator
{
class Grade
{
string _description;
float _percentEarned;
float _weight;
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
public float PercentEarned
{
get
{
return _percentEarned;
}
set
{
_percentEarned = value;
if (value < 0.0f || value > 100.0f)
{
//_percentEarned = 0;
Console.WriteLine("Percent earned was less than 0 or greater than 100 so value was set to 0.");
}
else
{
_percentEarned = value;
}
}
}
public float Weight
{
get
{
return _weight;
}
set
{
if (value < 0.0f || value > 100.0f)
{
//_weight = 0;
Console.WriteLine("Weight was less than 0 or greater than 100 so value was set to 0.");
}
else
{
_weight = value;
}
}
}
public float GetPercentOfFinalGrade()
{
float result = (_percentEarned * _weight) / 100;
return result;
}
}
}
all you need is to clear the console at the End of the Loop and make it Stay there for a While just to show user the output you would do something like this
i have Added like , 3000 means for 3000 milliseconds that are 3 seconds we will show the user error and then we will clear the output and show the menu again,use 3 seconds or 5 seconds(5000),what ever you want, and then clear the output
System.Threading.Thread.Sleep(3000);
Console.Clear();
static void Main(string[] args)
{
Student currentStudent = null;
bool running = true; // Logic 1
string input = "";
while (running)
{
// display menu
Console.WriteLine("Main menu: ");
Console.WriteLine("1. Create a student");
Console.WriteLine("2. Add a course to the current student");
Console.WriteLine("3. Remove a course from the current student");
Console.WriteLine("4. Add grades for a course");
Console.WriteLine("5. Display student info");
Console.WriteLine("6. Display grades for a course");
Console.WriteLine("7. Display all grades");
Console.WriteLine("8. Exit");
Console.Write("Enter a selection: (1 - 8): ");
input = Console.ReadLine().ToLower();
Console.WriteLine();
// handle choices
//------------------------------------------------------------------------
switch (input)
{
case "1":
case "create a student":
{
Console.Write("What is the students first name? ");
string firstName = Console.ReadLine();
Console.Write("What is the students last name? ");
string lastName = Console.ReadLine();
currentStudent = new Student(firstName, lastName);
Console.Write("How old is the student? ");
string studentAge = Console.ReadLine(); // Logic 2
int age;
while (!int.TryParse(studentAge, out age))
{
Console.Write("Please enter a number: ");
studentAge = Console.ReadLine();
}
currentStudent.Age = age;
Console.Write("What is the students address? ");
currentStudent.Address = Console.ReadLine();
Console.Write("What is the students email? ");
currentStudent.Email = Console.ReadLine();
Console.Write("What is the students phone number? ");
currentStudent.Phone = Console.ReadLine();
}
break;
case "2":
case "add a course to the current student":
{
if (currentStudent != null)
{
currentStudent.AddACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "3":
case "remove a course from the current student":
{
if (currentStudent != null)
{
currentStudent.RemoveACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "4":
case "add grades for a course":
{
if (currentStudent != null)
{
currentStudent.AddGradesForACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "5":
case "display student info":
{
if (currentStudent != null)
{
currentStudent.DisplayInfo();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "6":
case "display grades for a course":
{
if (currentStudent != null)
{
currentStudent.DisplayGradesForACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "7":
case "display all grades":
{
if (currentStudent != null)
{
currentStudent.DisplayAllGrades();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "8":
case "exit":
{
running = false; // Logic 6
}
break;
default:
return;
}
Console.WriteLine("You have chosen to exit");
//Console.ReadKey();
System.Threading.Thread.Sleep(3000);
Console.Clear();
}
}
i have following code, there are 2 classes, 'Account' and 'Program'. What i am trying to do here is just simulating a simple bank management console system where user can create instances of 'Account' class ( which are being stored in List<Account> accounts member variable ( Data structure ). I'am confused about why the account list is not updating when i add the Account object and access the accounts list in other methods ( like Login() ).
Please guide me. Thanks
namespace Banking_System
{
class Account
{
public Account(string f, string l, string id, string ph, string t, int bal, int no)
{
fname = f;
lname = l;
cnic = id;
phone = ph;
amount = bal;
acc_no = no;
}
public string fname { get; set; }
public string lname { get; set; }
public string cnic { get; set; }
public string phone { get; set; }
public string type { get; set; }
public int amount { get; set; }
public int acc_no { get; set; }
}
class Program
{
//private Program bank_instance;
private List<Account> accounts {get;set;}
static void Main(string[] args)
{
while (true)
{
Console.Clear();
Console.WriteLine("Welcome to the bank");
Console.WriteLine("====================\n");
Console.WriteLine("Please choose an option from the list below");
Console.WriteLine("============================================");
Console.WriteLine("e ñ Existing account");
Console.WriteLine("n ñ New account");
Console.WriteLine("c ñ close");
string input = Console.ReadLine();
Account acc;
Program bank_instance = new Program();
bank_instance.accounts = new List<Account>();
if (input == "n" || input == "N")
{
bank_instance.NewAccount();
int x = bank_instance.accounts.Count;
}
else if (input == "e" || input == "E")
{
acc = bank_instance.login();
if (acc == null)
{
Console.WriteLine("Account does not exists !");
continue;
}
bank_instance.operate(acc);
}
else if (input == "c" || input == "C")
{
Console.WriteLine("Goodbye !");
break;
}
else
{
Console.WriteLine("You entered the wrong character \nPlease enter the correct one");
}
}
}
private void operate(Account acc)
{
string input = null;
while (true)
{
Console.Clear();
Console.WriteLine("Choose an operation:");
Console.WriteLine("1) Check balance");
Console.WriteLine("2) Deposit cash");
Console.WriteLine("3) Withdraw cash");
Console.WriteLine("4) Close");
input = Console.ReadLine();
if (input == "1")
{
check_balance(acc.acc_no);
}
else if (input == "2")
{
deposite_cash(acc);
}
else if (input == "3")
{
withdraw(acc);
}
else if (input == "4")
{
Console.WriteLine("Goodbye !");
break;
}
else
{
Console.WriteLine("You entered the wrong character \nPlease enter the correct one");
}
}
}
private void check_balance(int inp)
{
foreach (Account a in accounts)
{
if (a.acc_no.Equals(inp))
{
Console.Write("Your Balance is : " + a.amount);
}
}
}
private void deposite_cash(Account acc)
{
int bal = 0;
Console.WriteLine("Enter the amount");
bal = int.Parse(Console.ReadLine());
if (bal <= 0)
{
Console.WriteLine("Please enter valid amount");
}
else
{
acc.amount += bal;
Console.WriteLine("Amount has been deposited successfully!");
}
}
private void withdraw(Account acc)
{
int bal = 0;
Console.WriteLine("Enter the amount");
bal = int.Parse(Console.ReadLine());
if (bal <= 0)
{
Console.WriteLine("Please enter valid amount");
}
else
{
acc.amount -= bal;
Console.WriteLine("Amount has been Withdrawn successfully!");
}
}
private void NewAccount()
{
Console.WriteLine("================================================================");
Console.WriteLine("Please fill in the following information to create a New Account");
Console.WriteLine("================================================================");
Console.WriteLine("1) First name");
string f_name = Console.ReadLine();
Console.WriteLine("2) Last Name");
string l_name = Console.ReadLine();
int check_length;
int id_card_no;
do
{
Console.WriteLine("3) National ID card Number (xxxxxxxxxxxxx)");
check_length = Console.ReadLine().Length;
id_card_no = Convert.ToInt32(check_length);
}
while (check_length != 13);
Console.WriteLine("4) Contact Number");
System.Int64 contact_no = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("5) Account type - (Current , Saving) ");
string account_type = Console.ReadLine();
Console.WriteLine("6) Initial amount to deposit (Minimum 50,000) ");
int ini_amount = int.Parse(Console.ReadLine());
if (ini_amount <= 50000)
{
Console.WriteLine(ini_amount);
}
else
{
Console.WriteLine("teri mehrbani");
}
// Generate a random number
Random rand = new Random();
Account acc = new Account(f_name, l_name, id_card_no.ToString(), contact_no.ToString(), account_type, ini_amount, rand.Next(00000, 55555));
accounts.Add(acc);
Console.WriteLine("Account created ! you Account number is : " + acc.acc_no + "\n Press any key to continue");
Console.Read();
}
private Account login()
{
int inp = 0;
Console.WriteLine("Enter your account number");
inp = int.Parse(Console.ReadLine());
foreach (Account a in accounts)
{
if (a.acc_no.Equals(inp))
{
Console.Write("Welcome !");
return a;
}
}
return null;
}
}
}
Every time you run your while loop, you're creating a new instance of bank_instance, and you initialize the bank_instance.accounts to a new List, which effectively erases all the data you've collected.
Instead, try initializing these things outside your loop, so they exist the next time through.
For example:
static void Main(string[] args)
{
Program bank_instance = new Program();
bank_instance.accounts = new List<Account>();
while (true)
{