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());
Related
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; }
}
I don't really understand arrays and I need to create a variable of type 'array of songs' then initialize it to a new Array so it can store 4 references to Songs. How would I then create a loop that would run enough times to fill the array whilst calling the InputSOngDetails() method and store the return value in that method?
namespace Songs
{
class Program
{
static void Main(string[] args) {
InputSongDetails();
}
static Song InputSongDetails()
{
Console.WriteLine("What is the name of your song");
string name = Console.ReadLine();
Console.WriteLine("What is the artists name");
string artist = Console.ReadLine();
int records;
Console.WriteLine("How many records did it sell");
while (!int.TryParse(Console.ReadLine(), out records) || records < 0)
{
Console.WriteLine("That is not valid please enter a number");
}
return new Song(name, artist, records);
}
}
}
This is my Songs class if needed
namespace Songs
{
class Song
{
string name;
string artist;
int copiesSold;
public Song(string name, string artist, int copiesSold)
{
this.name = name;
this.artist = artist;
this.copiesSold = copiesSold;
}
public Song()
{
}
public string GetArtist()
{
return artist;
}
public string GetDetails()
{
return $"Name: {name} Artist: {artist} Copies Sold: {copiesSold},";
}
public string GetCertification()
{
if (copiesSold<200000)
{
return null;
}
if (copiesSold<400000)
{
return "Silver";
}
if (copiesSold<600000)
{
return "gold";
}
return "Platinum";
}
}
}
Fist, initialize your array of songs with new Song[ length ], then a simple for-loop will suffice.
static void Main(string[] args)
{
Song[] songs = new Song[4];
for(int i = 0; i < songs.Length; i++)
{
songs[i] = InputSongDetails();
}
}
Or as the commenters suggest, just use a variable-length List<Song>.
static void Main(string[] args)
{
List<Song> songs = new List<Song>();
for(int i = 0; i < 4; i++)
{
songs.Add(InputSongDetails());
}
}
Once you've mastered the basics, you can also accomplish this with a bit of Linq (though I wouldn't actually recommend it in this case):
static void Main(string[] args)
{
var songs = Enumerable.Range(0, 4)
.Select(i => InputSongDetails())
.ToList();
}
This is not really an answer as much as it is a tip for getting input from the user in a console application which might be useful to you (well, the answer is in the last code snippet, but p.s.w.g has already covered that very well).
Since an interactive console session usually ends up with a lot of Console.WriteLine("Ask the user a question"); string input = Console.ReadLine();, and, as you've already done very well, include some validation on the input in some cases, I've found it handy to write the following methods below.
Each of them take in a string, which is the prompt for the user (the question), and return a strongly-typed variable that represents their input. Validation (when needed) is all done in a loop in the method (as you've done):
private static ConsoleKeyInfo GetKeyFromUser(string prompt)
{
Console.Write(prompt);
var key = Console.ReadKey();
Console.WriteLine();
return key;
}
private static string GetStringFromUser(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
public static int GetIntFromUser(string prompt = null)
{
int input;
int row = Console.CursorTop;
int promptLength = prompt?.Length ?? 0;
do
{
Console.SetCursorPosition(0, row);
Console.Write(prompt + new string(' ', Console.WindowWidth - promptLength - 1));
Console.CursorLeft = promptLength;
} while (!int.TryParse(Console.ReadLine(), out input));
return input;
}
With these methods in place, getting input is as simple as:
string name = GetStringFromUser("Enter your name: ");
int age = GetIntFromUser("Enter your age: ");
And it makes writing the method to get a Song from the user that much easier:
private static Song GetSongFromUser()
{
return new Song(
GetStringFromUser("Enter song name: "),
GetStringFromUser("Enter Artist name: "),
GetIntFromUser("Enter number of copies sold: "));
}
So now our main method just looks like (and this is the answer to your question):
private static void Main()
{
var songs = new Song[4];
for (int i = 0; i < songs.Length; i++)
{
songs[i] = GetSongFromUser();
}
Console.WriteLine("\nYou've entered the following songs: ");
foreach (Song song in songs)
{
Console.WriteLine(song.GetDetails());
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
Additionally, here are some suggestions for improving the Song class.
I am trying to be an educated lazy chemistry student, by making a C# program that can do chemistry calculation for me. In order to make the code, I have to understand well the procedures in chemistry class.
I am new to any kind of programming, C# is my first language.
The code works fine for 1 Element calculation, but not 2 Elements calculation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
MassCalculation myMassCalculation = new MassCalculation();
TwoMassCalculation myTwoMassCalculation = new TwoMassCalculation();
Console.WriteLine("How many elements are in the compound?");
string userMainInput = Console.ReadLine();
if (userMainInput == "1")
{
myMassCalculation.Amount1 = 1;
Console.WriteLine("What is the ELEMENT?");
string userInput1 = Console.ReadLine();
Elements element;
if (Enum.TryParse<Elements>(userInput1, true, out element))
{
switch (element)
{
case Elements.Na:
myMassCalculation.Element1 = 22.990;
break;
case Elements.Cl:
myMassCalculation.Element1 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount1 = Console.ReadLine();
int myAmount1 = int.Parse(userAmount1);
myMassCalculation.Amount1 = myAmount1;
myMassCalculation.DoCalculation();
resultOfMassCalculation(myMassCalculation);
}
if (userMainInput == "2")
{
Console.WriteLine("What is the First ELEMENT?");
string userInput1 = Console.ReadLine();
Elements element;
if (Enum.TryParse<Elements>(userInput1, true, out element))
{
switch (element)
{
case Elements.Na:
myMassCalculation.Element1 = 22.990;
break;
case Elements.Cl:
myMassCalculation.Element1 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount1 = Console.ReadLine();
int myAmount1 = int.Parse(userAmount1);
myMassCalculation.Amount1 = myAmount1;
Console.WriteLine("What is the Second ELEMENT?");
string userInput2 = Console.ReadLine();
if (Enum.TryParse<Elements>(userInput2, true, out element))
{
switch (element)
{
case Elements.Na:
myTwoMassCalculation.Element2 = 22.990;
break;
case Elements.Cl:
myTwoMassCalculation.Element2 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount2 = Console.ReadLine();
int myAmount2 = int.Parse(userAmount2);
myTwoMassCalculation.Amount2 = myAmount2;
myTwoMassCalculation.DoCalculation();
resultOfMassCalculation(myTwoMassCalculation);
}
Console.ReadLine();
}
private static void resultOfMassCalculation(MassCalculation calculation)
{
Console.Write("The Mass is {0}g/mol", calculation.DoCalculation());
}
}
enum Elements
{
Na,
Cl,
}
class MassCalculation
{
public double Element1 { get; set; }
public int Amount1 { get; set; }
public virtual double DoCalculation()
{
double result = Element1 * Amount1;
return result;
}
}
class TwoMassCalculation : MassCalculation
{
public double Element2 { get; set; }
public int Amount2 { get; set; }
public override double DoCalculation()
{
double result = Element1 * Amount1 + Element2 * Amount2;
return result;
}
}
}
Please help! I know it seems somewhat unprofessional. I have just started programming a week ago, and this is the best I can do. I need guidance.
The only elements defined in the code is Na and Cl, I am trying to calculate NaCl. When everything is in place, I will add more elements to the list, and many more different types of calculations.
I'll take constructive opinions.
Thank you so much in advance.
I refactored your code a little. It will work the same way, but wont crash on inappropriate user input
https://dotnetfiddle.net/CMQugr
using System;
using System.Collections.Generic;
namespace Test
{
public class Program
{
public static Dictionary<string, double> Elements = new Dictionary<string, double>
{
{"Na",22.990},
{"Cl",35.453}
};
public static void Main()
{
double result = 0;
int elemenCountInput;
do
{
Console.WriteLine("How many elements are in the compound?");
} while (!Int32.TryParse(Console.ReadLine(), out elemenCountInput));
for (int i = 0; i < elemenCountInput; i++)
{
string element;
do
{
Console.WriteLine("What is the {0} element", (i + 1));
element = Console.ReadLine();
} while (!Elements.ContainsKey(element));
int amount;
do
{
Console.WriteLine("How many");
} while (!Int32.TryParse(Console.ReadLine(), out amount));
result += Elements[element] * amount;
}
Console.Write("The Mass is {0}g/mol", result);
Console.ReadLine();
}
}
}
There is problem in the code when elements are two. You are assigning the first element value to "myMassCalculation' object and second element value to "myTwoMassCalculation". When you call "DoCalculation()" "myTwoMassCalculation.Element1' and "myTwoMassCalculation.Amount1" have no values. That's why it is giving wrong answer. Make the following changes and try:
if (Enum.TryParse<Elements>(userInput1, true, out element))
{
switch (element)
{
case Elements.Na:
myTwoMassCalculation.Element1 = 22.990;
break;
case Elements.Cl:
myTwoMassCalculation.Element1 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount1 = Console.ReadLine();
int myAmount1 = int.Parse(userAmount1);
myTwoMassCalculation.Amount1 = myAmount1;
I'd do something like:
Create a class for elements (name (string), whatever that number is (double/decimal)
Create a static dictionary of them of them indexed by name.
Loop through the parameters to Main (or loop around an input command) looking up each entry in the dictionary then perform the calculation.
Convert to LINQ if desired.
This is be a great approach and should teach you a lot. I'm not going to write it for you (time and desire), but I may come back later with an example.
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 wrote some code in wich it has a class named Cars as below:
public class Cars
{
public Cars()
{
string ma;
int pe;
Console.WriteLine("PLz put the car name:");
ma = Console.ReadLine();
Console.WriteLine("PLz put car no :");
pe = Convert.ToInt16( Console.ReadLine());
}
}
Now I want to create multiple objects of it like a list or an array.
I know this code and I don't know how to use a for loop for this in case it can create multiple cars automatically
Cars[] car = new Cars[10];
or
List <Cars>
The thing is I don't know how to use them, please help me if you can.
I think what you're looking for is this:
Cars[] car = new Cars[10];
for (int i = 0; i < 10; i++)
{
car[i] = new Cars();
}
or using a List<T>:
List<Cars> car = new List<Cars>();
for (int i = 0; i < 10; i++)
{
car.Add(new Car());
}
I suggest, however, that you move the Console functions outside of your class, and instead have a constructor like so:
public Cars(string ma, int pe)
{
// assign to properties, etc.
}
Something a bit like below, will help you. But like the guys have said, you need to start with basics, reading from books is always best.
namespace Cars
{
class Program
{
static void Main(string[] args)
{
List<Cars> carList = new List<Cars>();
Console.WriteLine("PLz put the car name:");
string ma = Console.ReadLine();
Console.WriteLine("PLz put car no :");
int pe = Convert.ToInt16(Console.ReadLine());
carList.Add(new Cars(ma,pe));
}
public class Cars
{
string ma;
int pe;
public Cars(string carName, int reg)
{
ma = carName;
pe = reg;
}
}
}
}