List containing class objects not working - c#

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)
{
...
}
}

Related

How to search element in LinkedList with custom object

I need to find a node with input from a customer in the linked list but I have an error CS1503. How can I solve a problem?
In this code, I create the LinkList name "customerList" to collect string data such as name, contact number, and payment from the user. After that, I need to find the contact number which input from the user to show data in the node and delete it. In code show that input in "searchCustomerDetail" cannot convert 'string' to ....
Error Message: Argument 1: cannot convert from 'string' to 'IFN564.Customer' [IFN564]csharp(CS1503)
public class Customer {
public string Name { get; set; }
public string Phone { get; set; }
public string Payment { get; set; }
public int[] Screening { get; set; }
public static LinkedList<Customer> customerList = new LinkedList<Customer>();
public static string input;
public static void addCustomerDetail() {
Console.WriteLine("Please enter your information detail");
Console.WriteLine("");
Console.Write("Full Name: ");
string inputName = Console.ReadLine();
Console.Write("Contact Number: ");
string inputPhone = Console.ReadLine();
Console.Write("Payment Method: ");
string inputPayment = Console.ReadLine();
Console.Clear();
Console.WriteLine("");
Console.WriteLine("Please check your information detail!!");
Console.WriteLine("");
Console.WriteLine($"Full Name: {inputName}");
Console.WriteLine($"Contact Number: {inputPhone}");
Console.WriteLine($"Payment Method: {inputPayment}");
Console.WriteLine("");
Console.WriteLine("Please 1 to confirm or 0 to cancel");
int input = Convert.ToInt32(Console.ReadLine());
switch (input) {
case 1:
insert(inputName, inputPhone, inputPayment);
break;
case 2:
Program.Main();
break;
}
}
public static void insert(string name, string phone, string payment) {
Console.WriteLine("");
Console.WriteLine("Please 1 to confirm buy ticket or 0 to cancel");
int input = Convert.ToInt32(Console.ReadLine());
Customer customerDetail = new Customer() {
Name = name,
Phone = phone,
Payment = payment,
};
switch (input) {
case 0: Program.Main(); break;
case 1:
customerList.AddLast(customerDetail);
Program.Main();
break;
}
}
public static void searchCunstomerDetail() {
Console.WriteLine("Please enter contact number!!");
Console.WriteLine("");
Console.Write("Contact number: ");
input = Console.ReadLine();
LinkedListNode<Customer> node = customerList.Find(input);
Console.WriteLine(node);
}
}
I try to use LinkListNode to find but It show error with input CS1503
you need to use LINQ where
var node = customerList.Where(c=>c.Phone == input).First();
The error is with this statement:
LinkedListNode<Customer> node = customerList.Find(input);
customerList.Find searches the customerList for an element (in this case, a Customer) that equals the argument provided to Find (in this case, the var, input). input is a string, not Customer, so it can't be used in Find here.
What you seemingly intend to do here is to find the Customer in customerList that has a Customer.Phone that equals the input string. To do so, you can use LINQ, as others have suggested:
LinkedListNode<Customer> node = customerList.FirstOrDefault(c => c.Phone == input);
The above expression will find the first element in the list that returns true for the provided function (predicate), and will return null if none match.

Taking user input as name of new class instance

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; }
}

List keeps getting reset to empty. How can I fix this?

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;
}
}
}
}

I want to know how to invoke a string input from another method

I'm new in c#, and I'm trying to make a text game in a console application. I did this code for an example because I want to know how to invoke a string input from another method
class Program
{
static void Main(string[] args)
{
b();
}
public static void b()
{
stops();
c();
}
public static string stops ()
{
string stop = Console.ReadLine();
//here i get the user input
Console.WriteLine(stop);
return stop;
}
public static void c()
{
string stop = stops();
Console.WriteLine("i need this:" + stop);
// here i want the user input
Console.ReadLine();
}
}
in this case, I didn't receive in the console the user input stop
I want to hold in my game the user name, but I'm using a lot of methods. In one method I ask the user his name, but I can't use his string in another method.
Now I'm trying to simplify my question, in the next example, the console application doesn't print here Console.WriteLine("your name is: " + name); this input string name = Console.ReadLine();
class Program
{
static void Main(string[] args)
{
Console.WriteLine("what is your name:");
userName();
string name = userName();
Console.WriteLine("your name is: " + name);
Console.ReadLine();
}
public static string userName ()
{
string name = Console.ReadLine();
return name;
}
}
The problem in your simple example is that you are calling the method twice - the first time you aren't capturing the output, and the second time you are. If you simply remove the first call to userName(), your code should work fine.
Here's a modified example:
static void Main()
{
string name = GetUserName();
Console.WriteLine("Hello, " + name + ". Nice to meet you!");
Console.ReadKey();
}
public static string GetUserName()
{
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
return name;
}
Output
Now, if you want to use the userName throughout your program, you might consider setting it as a class-level variable. This means that all the methods in your class will have access to it.
Notice also that now you don't have to capture the output of the GetUserName method, because it will set a variable that you have access to already. We just call GetUserName, and then the GreetUser method has access to it:
// Variable set at this scope will be accessible to the whole class
private static string userName;
static void Main()
{
GetUserName();
GreetUser();
Console.ReadKey();
}
public static void GetUserName()
{
Console.Write("Please enter your name: ");
userName = Console.ReadLine();
}
public static void GreetUser()
{
Console.WriteLine("Hello, " + userName + ". Nice to meet you!");
}
I think you already answer your own question in your code.
In this case, when you have stops() that return the user input and c() that calls stops() again, which will ask for user input again. Based on your question, you want to take a string input from another method, which you already did in the c(). If you are trying to ask user input once only, then you can remove the stops() method inside the b() method.
class Program
{
static void Main(string[] args)
{
Init();
}
public static void Init()
{
AskUserInput();
}
public static string stops()
{
string stop = Console.ReadLine();
//here i get the user input
Console.WriteLine(stop);
return stop;
}
public static void AskUserInput()
{
string stop = stops();
Console.WriteLine("i need this:" + stop);
}
}
Also, as Rob mentioned, it's good practice to name your method with proper name. As later on when you start dealing with large project, this will help you a lot.
I also removed the last Console.ReadLine as I'm not sure what it does.
I believe the code after you edited your question is just fine with one slightly change. You don't have to call twice the method userName(). The first time the program is waiting for your input is from when you are not assigning the returned value to any variable. Then it is waiting for input again and there is where stores de variable and give you an output.
You just have to comment the line before string name ...
Here is your code working: fiddle

How to retrieve input from a function

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());

Categories