I am trying to create a class in C# called customer, with 3 variables: name, initial deposit, and monthly deposit amount.
This is for a console program that takes user input for those three variables and keeps asking for more users until the user types nothing and presses enter.
However, the line
customer userInputName = new customer(userInputName, userInputInitial, userInputMonthly);
is giving me errors. The first userInputName is underlined saying "a local or parameter named 'userInputName' cannot be delcared in this scope because that name is used in an enclosing local scope to define a local or parameter". The second 'userInputName' says "Argument 1: cannot convert from 'lab4.Program.customer' to 'string' ".
The only way I can fix this is by changing the first 'userInputName' to something like customer1, but if I do that, I can't continuously make new customers if the user continues typing names.
Ideally, I want to be able to type something like customer.Bob.initialDeposit and have the program able to tell me what Bob's initial Deposit was, etc.
How can I achieve this, or what am I doing wrong?
using System;
namespace lab4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many months will the customer keep the money in the account?");
string monthsString = Console.ReadLine();
int months = Int32.Parse(monthsString);
bool run = true;
while (run)
{
Console.WriteLine("Enter new customer name: ");
string userInputName = Console.ReadLine();
if (userInputName == "")
{
run = false;
}
else
{
Console.WriteLine("Enter initial deposit amount: ");
string stringInitDeposit = Console.ReadLine();
int userInputInitial = Int32.Parse(stringInitDeposit);
Console.WriteLine("Enter montly deposit amount: ");
string stringMonthDeposit = Console.ReadLine();
int userInputMonthly = Int32.Parse(stringMonthDeposit);
customer userInputName = new customer(userInputName, userInputInitial, userInputMonthly);
}
}
}
public class customer
{
public string name;
public int initialDeposit;
public int monthlyDeposit;
public customer(string name, int initialDeposit, int monthlyDeposit)
{
this.name = name;
this.initialDeposit = initialDeposit;
this.monthlyDeposit = monthlyDeposit;
}
}
}
}
You have
string userInputName = Console.ReadLine();
and
customer userInputName = new customer(userInputName, userInputInitial, userInputMonthly);
You are attempting to reuse the same variable name. Pick a new one for the customer (since the name doesn't make sense for that, anyway), and update references to use that new variable name.
If you want to make multiple customers, add the new customer to an array. The variable can still be reused within the while loop.
Example:
// add this line outside (above) the while loop: (you will need to import the proper namespace for this: `using System.Collections.Generic;`)
List<Customer> newCustomers = new List<Customer>();
// I renamed this variable. add the line below to put the new customer into the list
customer newCustomer = new customer(userInputName, userInputInitial, userInputMonthly);
newCustomers.Add(newCustomer);
// now you have a list of new customers you can reference outside the while loop.
To get Bob's deposit you could something like the following:
using System;
using System.Collections.Generic;
using System.Linq;
(...)
var customers = new List<Customer>();
//Your logic to create customers here
var c1 = new Customer("Bob", 100, 10);
customers.Add(c1);
var c2 = new Customer("Bob", 200, 20);
customers.Add(c2);
var c3 = new Customer("Alice", 100, 10);
customers.Add(c3);
//Find all Bobs
var bobs = customers.Where(c => c.Name == "Bob");
foreach (var bob in bobs )
{
Console.WriteLine($"Bob's initial deposit is {bob.InitialDeposit}");
}
Please note that names of classes are normally capitalised, e.g. Customer.
It's also common to keep fields private in classes and use properties for public access.
Here is an variant of the Customer class:
public class Customer
{
public Customer(string name, int initialDeposit, int monthlyDeposit)
{
Name = name;
InitialDeposit = initialDeposit;
MonthlyDeposit = monthlyDeposit;
}
public string Name { get; }
public int InitialDeposit { get; }
public int MonthlyDeposit { get; }
}
Related
I'm currently learning C# and have assigned myself to make a program to help me understand OOP which essentially takes in values and assigns them to variables. The program takes in information about football players; the name, last name, position, and shirt number.
I'm trying to use getters and setters to ensure that a shirt number can only be used once. So i've set a list up that stores all the shirt numbers that are being used. The problem i'm having is: the list keeps getting reset and I have no idea why. After one value has been added, by the time the next one gets added, the list is empty again. This makes my if statement in the setter not work as the list does not contain any values.
Im sure this is a rookie error and should be shouting at me, but Im new to this language and am not really sure on all the ins and outs of it.
I haven't really tried much, and I cant find anything online as this seems to be a specific error that im having. I don't know enough about the language to properly troubleshoot this, and what I do know about the language tells me this should work.
namespace RandomObject
{
class Program
{
static void Main(string[] args)
{
Player player1 = new Player("Lucas", "Torreira", "Defensive Midfielder", 11);
Player player2 = new Player("Alexandre", "Lacazette", "Striker", 9);
Player player3 = new Player("Pierre-Emerick", "Aubameyang", "Striker", 14);
Player player4 = new Player();
Console.Write("Please enter new players first name: ");
player4.Name = Console.ReadLine();
Console.Write("Please enter new players last name: ");
player4.LastName = Console.ReadLine();
Console.Write("Please enter new players position: ");
player4.Position = Console.ReadLine();
Console.Write("Please enter new players shirt number: ");
player4.ShirtNo = Convert.ToInt32(Console.ReadLine());
player1.PrintPlayerInfo();
player2.PrintPlayerInfo();
player3.PrintPlayerInfo();
player4.PrintPlayerInfo();
Console.ReadKey();
}
}
}
class Player
{
private List<int> shirtNumbers = new List<int>();
private int _shirtNo;
public void PrintPlayerInfo() //<access modifier> <return type> <method name>(parameters)
{
Console.WriteLine("Player: {0} {1}", Name, LastName);
Console.WriteLine("Position: {0}", Position);
Console.WriteLine("Shirt No.: {0}\n", _shirtNo);
}
public Player()
{
Name = string.Empty;
LastName = string.Empty;
Position = string.Empty;
_shirtNo = 0;
}
public Player(string name, string lastName, string position, int shirtNo)
{
Name = name;
LastName = lastName;
Position = position;
_shirtNo = shirtNo;
AddToList(_shirtNo);
}
private void AddToList(int newNumber)
{
shirtNumbers.Add(newNumber);
Console.WriteLine(shirtNumbers[0]);
}
public string Name { get; set; }
public string LastName { get; set; }
public string Position { get; set; }
public int ShirtNo
{
get { return _shirtNo; }
set
{
if (shirtNumbers.Contains(value) == false)
{
_shirtNo = value;
}
else
{
_shirtNo = 0;
}
}
}
}
}
In my main method I declare 3 instances of the class, with shirt numbers 11, 9, and 14. So when it comes to inputting one into the console using readlines and such, if I were to enter 14, the shirt number should be set to 0. However if I enter 10, it should be set to 10.
The Player class now does two things: it holds information about one player, and it contains a list of shirt numbers for all players. One of those two doesn't belong there.
The private List<int> shirtNumbers = new List<int>(); is an instance variable, meaning each player has its own list of shirt numbers. So if you assign a shirt to player X, the list in player Y's instance has no notion of this, enabling you to assign shirt N to both player X and Y.
Sure, you could fix this by declaring the list to be static, but that's just bad design; the Player class needs to know about one player, not all of them.
So instead keep this shirt number check outside your player class. Declare the shirt list before the player list, and modify your code accordingly.
You should have a static list of numbers. Otherwise every player has its own list of valid numbers.
class Player
{
private static List<int> shirtNumbers = new List<int>();
private int _shirtNo;
}
This way you have a single list that all your player share.
You are using the AddToList method on your constructor to add the shirtlist number which is correctly but when you are defining ShirtNo setter you are not adding to the list
Fix :
public int ShirtNo
{
get { return _shirtNo; }
set
{
if (shirtNumbers.Contains(value) == false)
{
_shirtNo = value;
AddToList(value)
}
else
{
_shirtNo = 0;
}
}
}
i copied your code to debug in my local machine. Few changes that needs to be done to your
1.The shirtNumbers list has to be declared static , if not for every instance of player class will have List (private static List shirtNumbers = new List();)
You are assigning values to the variable directly and not to the property in both the constructors.(getter setter is called property in C#).Hence the if condition inside setter wont be called.
class Player
{
private static List<int> shirtNumbers = new List<int>();
private int _shirtNo;
public void PrintPlayerInfo()
{
Console.WriteLine("Player: {0} {1}", Name, LastName);
Console.WriteLine("Position: {0}", Position);
Console.WriteLine("Shirt No.: {0}\n", _shirtNo);
}
public Player()
{
Name = string.Empty;
LastName = string.Empty;
Position = string.Empty;
ShirtNo = 0;
}
public Player(string name, string lastName, string position, int shirtNo)
{
Name = name;
LastName = lastName;
Position = position;
ShirtNo = shirtNo;
AddToList(_shirtNo);
}
private void AddToList(int newNumber)
{
shirtNumbers.Add(newNumber);
Console.WriteLine(shirtNumbers[0]);
}
public string Name { get; set; }
public string LastName { get; set; }
public string Position { get; set; }
public int ShirtNo
{
get { return _shirtNo; }
set
{
if (shirtNumbers.Contains(value) == false)
{
_shirtNo = value;
}
else
{
_shirtNo = 0;
}
}
}
}
A quick question on OOP. I am using a list together with a class and class constructor. So I use the class constructor to define the data set and then add each record to my list as the user creates them.
My questions is once the data is in the list and say I want to alter something is it good practice to find the record, create an instance using that record and then use my class methods to do whatever needs doing - and then put it back in the list?
For example below I have my class with constructor. Lets say I only want the system to release strCode if the Privacy field is set to public. Now just using Instances I would use for example Console.WriteLine(whateverproduct.ProductCode) but if the record is already in a list do i take it out of the list - create an instance and then use this method?
class Product
{
private String strCode;
private Double dblCost;
private Double dblNet;
private String strPrivacy;
public Product(String _strCode, Double _dblCost, Double _dblNet, String _strPrivacy)
{
strCode = _strCode;
dblCost = _dblCost;
dblNet = _dblNet;
strPrivacy = _strPrivacy;
}
public string ProductCode
{
get
{
if (strPrivacy == "Public")
{
return strCode;
}
else
{
return "Product Private Can't release code";
}
}
}
Lets say we have the following:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Amount { get; set; }
private string _test = "Some constant value at this point";
public string GetTest()
{
return _test;
}
public void SetTest()
{
//Nothing happens, you aren't allow to alter it.
//_test = "some constant 2";
}
}
public class Program
{
public static void Main(string[] args)
{
List<Test> listOfTest = new List<Test>()
{
new Test() {Id = 0, Name = "NumberOne", Amount = 1.0M},
new Test() {Id = 1, Name = "NumberTwo", Amount = 2.0M}
};
Test target = listOfTest.First(x => x.Id == 0);
Console.WriteLine(target.Name);
target.Name = "NumberOneUpdated";
Console.WriteLine(listOfTest.First(x => x.Id == 0).Name);
Console.WriteLine(listOfTest.First(x => x.Id == 0).GetTest());//This will alsways be "Some constant value at this point";
Console.ReadLine();
}
}
Technically you could do away with the SetTest method entirely. However, I included it to demonstrate, what it would look like, if you wanted to alter _test.
You don't want to ever create a new instance of a class, you already have an instance of. you can just alter the class where it is allowed by the author of the class, where you need to. And keep that class reference for as long as you need it. Once you are done, the reference will be garbage collected, once the program finds no active reference to your object(instance).
I am developing a C# Android that takes the user input and add it to a database, then in another Activity, it displays the user input with an option to edit his input again.
So I have 2 activities and 1 public class which links them together. I am using SQLLite to save the user input into a database (in the MainActivity.cs) then (in the secondActivity) it retrieves the saved value (which is the user input) from the public database (located in the public class called Class1) and displays it in a Textview.
Class1.cs
namespace App
{
public class Class1
{
public static string dpPath= Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user.db3");
public void Insert(string Quantity, string name)
{
var db = new SQLiteConnection(Class1.dpPath);
var logintable = new LoginTable();
logintable.quantity = Quantity;
logintable.name = name;
db.Insert(logintable);
}
public void edit(string Quantity)
{
var db = new SQLiteConnection(Class1.dpPath);
var logintable = new LoginTable();
logintable.quantity = Quantity;
db.Update(logintable);
}
public void delete(int id)
{
var db = new SQLiteConnection(Class1.dpPath);
var logintable = new LoginTable();
logintable.id = id;
db.Delete(logintable);
}
public Class1()
{
//Creating database, if it doesn't already exist
if (!File.Exists(Class1.dpPath))
{
var db = new SQLiteConnection(Class1.dpPath);
db.CreateTable<LoginTable>();
}
}
public class LoginTable
{
[PrimaryKey, AutoIncrement, Column("_Id")]
public int id { get; set; } // AutoIncrement and set primarykey
[MaxLength(25)]
public string quantity { get; set; }
[MaxLength(15)]
public string name { get; set; }
public LoginTable()
{
}
}
}
MainActivity.cs
Class1 cl = new Class1():
cl.Insert(input.ToString(), name.ToLower());
SecondActivity.cs
Class1 cl = new Class1():
cl.edit(input.ToString());
var db = new SQLiteConnection(Class1.dpPath);
var table = db.Table<Class1.LoginTable>();
foreach( var item in table) {
textView.Text += item.name + " " + item.quantity;
}
Well, I am getting in the textview in the secondActivity, the input that was entered the first time (in the MainActivity) and not the one which was edited later in the SecondActivity. I thought that maybe because I have created two different instance of the Class1 and each one is working with a different Table. In addition, I have tried to initialise a public static instance of the Class1 inside the Class1 itself like that:
public class Class1 { public static Class1 cl = new Class1(); }
but did not work either, the textview is still displaying the original input and not the edited one. I need to be able to edit the database from each activitie.. Please help me to find a solution.
UPDATE
I have created a new class Class2 and I have initialise inside it a new instance of Class1 like that:
public class Class2
{
public static Class1 cl = new Class1();
}
And then i have tried to access this instance of the class1 in the Main and second activity, so in the Main my code are:
Class2.cl.Insert(input.ToString(), name.ToLower());
and in the second activity my code are:
Class2.cl.edit(input.ToString());
var db = new SQLiteConnection(Class1.dpPath);
var table = db.Table<Class1.LoginTable>(); // The issue is in this line
foreach( var item in table) {
textView.Text += item.name + " " + item.quantity;
}
So now the issue I think is in the secondActivity, the var table is getting only one table which is the one where the original input in the Main activity is stored, and when updating the value in the second activity, it is not considering the second table which stores the edited input. But still i don't know how to solve this.
On first glance it appears that your Edit() method is not correct. You have this:
public void edit(string Quantity)
{
var db = new SQLiteConnection(Class1.dpPath);
var logintable = new LoginTable();
logintable.quantity = Quantity;
db.Update(logintable);
}
But you have no way to quantify which item in the database that you wish to update; you're just creating a new item and then trying to update the table with that item. You should instead add some way to select the item you wish to edit, like this example:
public void Edit(int id, string quantity)
{
var db = new SQLiteConnection(Class1.dbPath);
var table = db.Table<Class1.LoginTable>();
var itemToEdit = table.First(f=>f.Id == id);
itemToEdit.quantity = quantity;
db.Update(itemToEdit);
}
As you can see, the example above gets the item from your table, edits the item and updates your table with the data you gave it.
Your Delete() method should follow a similar path, instead of instantiating a new object just to delete it.
Also about your update, you should consider researching the Singleton pattern. Here is a better way to handle a static object than your Class1/Class2 implementation. In your Class1 class, add the field:
public static readonly Class1 Instance = new Class1()
And then reference your instance from other classes like this:
Class1.Instance.Insert(input.ToString(), name.ToLower());
This way there is no way for you to accidentally create a new instance of Class1.
I am working on a small C# program that will store student records in a list. I need to use a class to hold each student record, which is the top class in my code sample below.
If the user chooses to create a new record, I place their input into a studentRecord variable and then add it to the recordList. However, when I attempt to display the number of student records currently available using Count(), the program does nothing except re-display the menu, as if totally ignoring my command to display. I think something is wrong with how/where I declared the list, or with how I create a new StudentRecord object each time the menu is run.
Also, all three methods must stay in the first class. Is there any way to fix this?
public class StudentRecord
{
//Declare the various fields of the class
private string strFirstName;
private string strLastName;
private int intCourses;
private int intCreditHours;
List<StudentRecord> lstRecords = new List<StudentRecord>();
//Declare the properties of the class, since the fields are private
public string StrFirstName
{
get
{
return strFirstName;
}
set
{
strFirstName = value;
}
}
public string StrLastName
{
get
{
return strLastName;
}
set
{
strLastName = value;
}
}
public int IntCourses
{
get
{
return intCourses;
}
set
{
intCourses = value;
}
}
public int IntCreditHours
{
get
{
return intCreditHours;
}
set
{
intCreditHours = value;
}
}
//Declare a default constructor
public StudentRecord()
{
}
//Declare a constructor that takes the four necessary parameters, and set the class
// properties equal to the respective parameters
public StudentRecord(string firstName, string lastName, int courses, int creditHours)
{
strFirstName = firstName;
strLastName = lastName;
intCourses = courses;
intCreditHours = creditHours;
}
//Declare a method to perform the adding a student record function
public void mtdAddStudentRecord()
{
//These variables temporarily hold the various user inputs
string strInputFirstName;
string strInputLastName;
int intInputCourses;
int intInputCreditHours;
//Prompt the user to enter the student's first name
Console.Write("Please enter the first name: ");
strInputFirstName = Console.ReadLine();
//Prompt the user to enter the student's last name
Console.Write("Please enter the last name: ");
strInputLastName = Console.ReadLine();
//Prompt the user to enter the student's number of courses
Console.Write("Please enter the number of courses: ");
intInputCourses = int.Parse(Console.ReadLine());
//Prompt the user to enter the student's completed credit hours
Console.Write("Please enter the number of completed credit hours: ");
intInputCreditHours = int.Parse(Console.ReadLine());
//Add the new student record to the list, using the paramaters of the second
// class constructor
lstRecords.Add(new StudentRecord(strInputFirstName, strInputLastName,
intInputCourses, intInputCreditHours));
}
//Declare a method to perform the display student information option
public void mtdDisplayStudentInformation()
{
Console.WriteLine("Capacity: {0}", lstRecords.Count);
}
//Declare a method to perform the edit student information option
public void mtdEditStudentInformation()
{
//TODO
}
}
public class Program
{
public static void Main(string[] args)
{
//Declare and initialize a variable to store the user menu choice
string strMenuChoice;
strMenuChoice = "";
//Perform the necessary menu option while the user has NOT chosen to exit
do
{
//Call the reset method to clear the screen and display the header
mtdResetConsole();
//Display a menu to the user
Console.Write("Please choose an option to perform:" +
"\n - A) Display a list of existing students" +
"\n - B) Add a new student record" +
"\n - C) Edit an existing student record" +
"\n - D) Exit the program" + "\n\n" + " ");
//Store the user reply
strMenuChoice = Console.ReadLine().ToLower();
//Create a new StudentRecord object, and use it to call the various methods
// as chosen by the user
StudentRecord studentRecord = new StudentRecord();
//Determine which option was chosen, and take the appropriate action
switch (strMenuChoice)
{
case "a":
//TODO - Necessary code for option A
mtdResetConsole();
//Perform the "view student records" method
studentRecord.mtdDisplayStudentInformation();
break;
case "b":
//TODO - Necessary code for option B
mtdResetConsole();
//Perform the "add student record" method
studentRecord.mtdAddStudentRecord();
break;
case "c":
//TODO - Necessary code for option C
break;
case "d":
//Exit the program
Environment.Exit(0);
break;
default:
mtdResetConsole();
Console.WriteLine("Error" + "\n" +
" - Please choose a valid option from the list");
//Pause the code from executing for 2.5 seconds, so that the error
// message will be displayed
System.Threading.Thread.Sleep(2500);
break;
}
}
while (strMenuChoice.ToLower() != "d");
}
//Declare a method to reset the console with a blank screen and header
public static void mtdResetConsole()
{
Console.Clear();
Console.WriteLine("CONESTOGA STUDENT RECORDS" + "\n");
}
}
First, put this outside do while
StudentRecord studentRecord = new StudentRecord();
Putting this inside do while means that the object will reset in every loop.
2nd, try to put something like Console.ReadLine() on mtdDisplayStudentInformation method to hold the screen.
public void mtdDisplayStudentInformation()
{
Console.WriteLine("Capacity: {0}", lstRecords.Count);
Console.ReadLine();
}
Kendall, try to separate the logic of your "Records" and your "List of records".
In the case bellow, you have a "list of records" for each record you create.
Suggestions are you create a static variable to make sure it is always the same list on all "Records" or you separate as bellow:
public class StudentRecord
{
//Declare the various fields of the class
private string strFirstName;
private string strLastName;
private int intCourses;
private int intCreditHours;
...
}
public class Program
{
private List<StudentRecord> records = new List<StudentRecord>();
public static void Main(string[] args)
{
...
}
}
I have the next code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Maman15cs
{
public class ClassRoom
{
public string ClassNumber;
public int NumberofPlaces;
public int[,] DayandHour = new int[6,8];
public void AddClassRoom()
{
Console.WriteLine("Enter the Class number, the Number of places\n");
ClassNumber = Console.ReadLine().ToString();
NumberofPlaces = int.Parse(Console.ReadLine());
Console.WriteLine("Good, now enter the Day(1, 2, 3, 4, 5, 6) and after that you put the courses' number that are that day (In Order)");
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 8; j++)
{
DayandHour[i,j] = int.Parse(Console.ReadLine());
}
}
}
}
public class Course
{
public string CourseName;
public int CourseNumber;
public int StudentsNumber;
public string TeacherName;
public string ClassNumber;
// Tuple<string, int, int, string, string>
public void AddCourse(Course *course)
{
Console.WriteLine("Enter the Course's name, course's number, students number, teacher's name, and class' number\n");
CourseName = Console.ReadLine().ToString();
CourseNumber = int.Parse(Console.ReadLine());
StudentsNumber = int.Parse(Console.ReadLine());
TeacherName = Console.ReadLine().ToString();
ClassNumber = Console.ReadLine().ToString();
}
}
public class Program
{
void Main()
{
Course[] course = new Course[1000];
ClassRoom[] classroom = new ClassRoom[1000];
Course* coursePointer;
int actionChoice;
int courseCount = 0, classroomCount = 0;
loop:
Console.WriteLine("What do you want to do? (Enter number): \n 1) Add a new Course \n 2)Add a new class room \n 3)Add an existing class to an existing classroom \n 4)Read the information of a specific classroom \n 5)Read the information of all the classrooms \n 6)Read the information of a specific course \n 7)Delete a specific course \n 8)Update courses in the Time Table \n 9)Exit the program \n");
actionChoice = int.Parse(Console.ReadLine());
switch (actionChoice)
{
case 1: //Add a new Course
// course[classroomCount].AddCourse();
break;
}
goto loop;
}
}
}
And I want the AddCourse function to return or use the pointer to add the input to the variable course, I tried some things like list<> but I'm not that experienced with this.
Change AddCourse to create a new Course and return it.
public Course AddCourse()
{
var course = new Course();
course.CourseName = Console.ReadLine().ToString();
// ... more readlines
return course;
}
In Main:
List<Course> courses = new List<Course>();
case 1: courses.Add(AddCourse()); break;
I had similar problems after switch to C# from C :)
First, you can replace Course[] course = new Course[1000]; with var course = new List<Course>();. List<T> is much better for the most scenaros - it has no exact size, you can add any numer of elements 'on the fly', on any position.
Second, all class instances passed as reference. Pointers are usable only in some rare scenarous.
Third. goto almost never used in C# too. There are tons of loops, enumerators etc in the language - foreach, while, for
Last. In your case I would do it in this way:
public class Course
{
public string CourseName;
public int CourseNumber;
public int StudentsNumber;
public string TeacherName;
public string ClassNumber;
public static Course ReadCourse()
{
var rez = new Course();
Console.WriteLine("Enter the Course's name, course's number, students number, teacher's name, and class' number\n");
rez.CourseName = Console.ReadLine().ToString();
rez.CourseNumber = int.Parse(Console.ReadLine());
rez.StudentsNumber = int.Parse(Console.ReadLine());
rez.TeacherName = Console.ReadLine().ToString();
rez.ClassNumber = Console.ReadLine().ToString();
return rez;
}
}
public class Program
{
void Main()
{
var courses = new List<Course>();
int actionChoice;
while(1=1)
{
Console.WriteLine("What do you want to do? (Enter number): \n 1) Add a new Course \n 2)Add a new class room \n 3)Add an existing class to an existing classroom \n 4)Read the information of a specific classroom \n 5)Read the information of all the classrooms \n 6)Read the information of a specific course \n 7)Delete a specific course \n 8)Update courses in the Time Table \n 9)Exit the program \n");
actionChoice = int.Parse(Console.ReadLine());
switch (actionChoice)
{
case 1: //Add a new Course
var new_course = Course.ReadCourse();
courses.Add(new_course);
break;
case 9: // Exit
return;
default:
Console.WriteLine("Wrong input");
}
}
}
}
What is interesting here. Static method Course.ReadCourse which reads and return new instance of Course. default selector in switch. return to exit the app. List<T> as a storage for courses. new Course() command uses implicit constructor created automatically because no any constructors were defined.
First, set up a list to hold all your courses, and not necessarily an array (unless you really need an array):
List<Course> Courses = new List<Courses>();
Change your AddCourse method return a newly instantiated Course object:
Public Course AddCourse(){
Course newCourse = new Course();
<logic to populate the object>
return newCourse;
}
Inside your loop where you're adding courses, just do something similar to this:
Courses.add(AddCourse());
Then you can use whatever looping structure to go through all the courses or linq to get a specific one you need.
---EDIT--
Since you're stuck with the way your Course class is set up (which is not best practice btw), you will need to change the AddCourse method to something like this:
public class Course
{
public string CourseName;
public int CourseNumber;
public int StudentsNumber;
public string TeacherName;
public string ClassNumber;
public void AddCourse()
{
Console.WriteLine("Enter the Course's name, course's number, students number, teacher's name, and class' number\n");
this.CourseName = Console.ReadLine().ToString();
this.CourseNumber = int.Parse(Console.ReadLine());
this.StudentsNumber = int.Parse(Console.ReadLine());
this.TeacherName = Console.ReadLine().ToString();
this.ClassNumber = Console.ReadLine().ToString();
}
}
Then the call in your looping method will need to be like this:
Course NewCourse = new Course();
Courses.Add(NewCourse.AddCourse());