This question already has answers here:
Does not exist in current context (Visual C#)
(4 answers)
Closed 5 years ago.
I'm very beginner when it comes to programming c#, there's two variables in a formula which aren't parsing as integers although i declared them within the main function. I have multiple methods achieving small tasks and it doesn't seem to be linking the main variable to the method one, the rest of the code doesn't have any errors so i'm not sure why it's not doing the formula. (I'll have to post all the code in order to show u)
public static void Main()
{
int income = 0;
int children = 0;
int tax = 0;
AskForIncome(income);
NoChild(children);
CalculateTax(tax);
ExitProgram();
}
public static void AskForIncome(int income)
{
Console.WriteLine("What is your total income: ");
string testNum = Console.ReadLine();
bool dummyBool = int.TryParse(testNum, out income);
if (dummyBool)
{
Console.WriteLine();
}
else if(income < 0)
{
Console.WriteLine("Your income cannot be negative.");
}
else
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
}
}
public static void NoChild(int children)
{
Console.WriteLine("How many children do you have: ");
string testChild = Console.ReadLine();
bool dummyBool2 = int.TryParse(testChild, out children);
if (dummyBool2)
{
Console.WriteLine();
}
else if(children < 0)
{
Console.WriteLine("You must enter a positive number.");
}
else
{
Console.WriteLine("You must enter a valid number.");
}
}
public static void CalculateTax(int tax)
{
tax = income - 10000 - (children * 2000);
if (tax < 0)
{
Console.WriteLine("You owe no tax.");
}
else
{
Console.WriteLine("You owe a total of $" + tax + " tax.");
}
}
c# its oop language, in your example looks like you developed in c,
First of all you need to do a class that will have all the variables and functions\methods you need semething like:
public class Employ
{
public int income {get; set;}
public int children {get; set}
public int tax {get; set};
public static void AskForIncome()
{
Console.WriteLine("What is your total income: ");
string testNum = Console.ReadLine();
bool dummyBool = int.TryParse(testNum, out income);
if (dummyBool)
{
Console.WriteLine();
}
else if (income < 0)
{
Console.WriteLine("Your income cannot be negative.");
}
else
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
}
}
public static void NoChild()
{
Console.WriteLine("How many children do you have: ");
string testChild = Console.ReadLine();
bool dummyBool2 = int.TryParse(testChild, out children);
if (dummyBool2)
{
Console.WriteLine();
}
else if (children < 0)
{
Console.WriteLine("You must enter a positive number.");
}
else
{
Console.WriteLine("You must enter a valid number.");
}
}
public static void CalculateTax()
{
tax = income - 10000 - (children * 2000);
if (tax < 0)
{
Console.WriteLine("You owe no tax.");
}
else
{
Console.WriteLine("You owe a total of $" + tax + " tax.");
}
}
}
and from main create employ object and do all what you need but learn about oop programming it's must.
Related
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 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);
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)
{