Adding an Additional Struct to hold data which then prints out in the console window - c#

I have been given this code to change, I have already added a struct with the initial student information in it and it runs fine the code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Program
{
class Student
{
public struct student_data
{
public string forename;
public string surname;
public string prog_title;
public string prog_code;
public int id_number;
public float averageGrade;
}
static void populateStruct(out student_data student, string fname, string surname, string prog_title, string prog_code, int id_number)
{
student = new student_data();
student.forename = fname;
student.surname = surname;
student.prog_title = prog_title;
student.prog_code = prog_code;
student.id_number = id_number;
student.averageGrade = 0.0F;
}
static void Main(string[] args)
{
student_data[] students = new student_data[4];
populateStruct(out students[0], "Mark", "Anders", "Comp", "CIS2117", 0);
printStudent(students[0]);
populateStruct(out students[1], "Tom", "Jones", "Comp", "CIS2117", 1);
printStudent(students[1]);
populateStruct(out students[2], "Tim", "Jones", "Comp", "CIS2117", 2);
printStudent(students[2]);
populateStruct(out students[3], "Tim", "Bones", "Comp", "CIS2117", 3);
printStudent(students[3]);
}
void printAllStudent(student_data student)
{
for (int i = 0; i <= 3; i++)
{
Console.WriteLine(i);
}
}
static void printStudent(student_data student)
{
Console.WriteLine("Name: " + student.forename + " " + student.surname);
Console.WriteLine("Id: " + student.id_number);
Console.WriteLine("AV grade: " + student.averageGrade);
Console.WriteLine("Course Title: " + student.prog_title);
Console.WriteLine("Course Code: " + student.prog_code);
}
}
}
But I was tasked with adding another Struct to hold module_data which I've done, I've also created a new method to populate the module_data array. But when I run the program only one error shows up and nothing happens?
It is meant to WriteLine all the elemmnts in the arrays in the console screen but will not build and produces this error:
'Error 1 The type or namespace name 'module_data' could not be found (are you missing a using directive or an assembly reference?)'
The Code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Program
{
class Student
{
public struct student_data
{
public string forename;
public string surname;
public string prog_title;
public string prog_code;
public int id_number;
public float averageGrade;
}
public struct module_data
{
public string module_code;
public string module_title;
public int module_mark;
}
static void populateStruct(out student_data student, string fname, string surname, string prog_title, string prog_code, int id_number)
{
student = new student_data();
student.forename = fname;
student.surname = surname;
student.prog_title = prog_title;
student.prog_code = prog_code;
student.id_number = id_number;
student.averageGrade = 0.0F;
}
static void populateModule(out module_data module, string mcode, string mname, int (score)
{
module = new module_data();
module.module_code = mcode;
module.module_title = mname;
module.module_mark = score;
}
static void Main(string[] args)
{
{
student_data[] students = new student_data[5];
populateStruct(out students[0], "Mark", "Anderson", "Comp", "CIS2117", 0);
printStudent(students[0]);
populateStruct(out students[1], "Tom", "Jones", "Comp", "CIS2117", 1);
printStudent(students[1]);
populateStruct(out students[2], "Tim", "Jones", "Comp", "CIS2117", 2);
printStudent(students[2]);
populateStruct(out students[3], "Tim", "Bones", "Comp", "CIS2117", 3);
printStudent(students[3]);
}
{
module_data[] modules = new module_data[4];
populateStruct(out modules[0], "7", "App Dev", "56", 0);
printStudent(modules[0]);
populateStruct(out modules[1], "7", "App Dev", "56", 1);
printStudent(module[1]);
populateStruct(out modules[2], "7", "App Dev", "56", 2);
printStudent(modules[2]);
populateStruct(out modules[3], "7", "App Dev", "56", 3);
printStudent(modules[3]);
Console.ReadKey();
}
}
void printAllStudent(student_data student)
{
for (int i = 0; i <= 3; i++)
{
Console.WriteLine(i);
}
}
static void printStudent(student_data student)
{
Console.WriteLine("Name: " + student.forename + " " + student.surname);
Console.WriteLine("Id: " + student.id_number);
Console.WriteLine("AV grade: " + student.averageGrade);
Console.WriteLine("Course Title: " + student.prog_title);
Console.WriteLine("Course Code: " + student.prog_code);
Console.WriteLine("Module Code: " + modules.mcode);
Console.WriteLine("Module Name: " + modules.mname);
Console.WriteLine("Score: " + modules.score);
}
}
}
In all truth not sure where I've gone wrong, any help or advice would be appreciated.

I'm not sure if a module is something a student has. This answer has them independent. Although the code needs additional work this will at least clean up your code and get you started. There are naming conventions that aren't followed here and other standards.
I would suggest you write one small piece of functionality and get that to work before moving on to something else. You had many errors in your code which wouldn't compile. Fixing an error as it occurs and testing small pieces will help you figure out what the problem is.
The links below are to explain comments in the code
Choosing Between Class and Struct
Default constructors
How to: Initialize Objects by Using an Object Initializer
Array Class showing it implements IEnumerable
class Program
{
//Use a class instead of a struct to store your data in most cases... see link
public class Student
{
public string forename { get; set; }
public string surname { get; set; }
public string prog_title { get; set; }
public string prog_code { get; set; }
public int id_number { get; set; }
public float averageGrade { get; set; }
//I ommited the defualt {} constructor so this is your only choice to create a new class
//you may want to choose to put it back in for more flexibility...see link
public Student(string fname, string surname, string prog_title, string prog_code, int id_number)
{
forename = fname;
this.surname = surname;
this.prog_title = prog_title;
this.prog_code = prog_code;
this.id_number = id_number;
averageGrade = 0.0F;
}
}
public class module_data
{
public string module_code { get; set; }
public string module_title { get; set; }
public int module_mark { get; set; }
public module_data(string mcode, string mname, int score)
{
module_code = mcode;
module_title = mname;
module_mark = score;
}
}
static void Main(string[] args)
{
//I'm initializing the array using object initialization syntax ... see link
Student[] students = new Student[4]
{
new Student( "Mark", "Anderson", "Comp", "CIS2117", 0),
new Student( "Tom", "Jones", "Comp", "CIS2117", 1),
new Student ("Tim", "Jones", "Comp", "CIS2117", 2),
new Student( "Tim", "Bones", "Comp", "CIS2117", 3)
};
module_data[] modules = new module_data[4]
{
new module_data( "7", "App Dev", 0),
new module_data( "7", "App Dev", 1),
new module_data("7", "App Dev", 2),
new module_data("7", "App Dev", 3)
};
printAllStudent(students);
Console.ReadKey();
}
//Because an array implements IEnumerable you should use a foreach loop instead of a for loop
static void printAllStudent(Student[] students)
{
foreach (Student s in students)
{
printStudent(s);
}
}
//You could pass a null in here and this would have a run-time error.
//It would be safer to check if student!=null here first (but I left it for you)
static void printStudent(Student student)
{
Console.WriteLine("Name: " + student.forename + " " + student.surname);
Console.WriteLine("Id: " + student.id_number);
Console.WriteLine("AV grade: " + student.averageGrade);
Console.WriteLine("Course Title: " + student.prog_title);
Console.WriteLine("Course Code: " + student.prog_code);
}
static void printModule(module_data m)
{
Console.WriteLine("Module Code: " + m.module_code);
Console.WriteLine("Module Name: " + m.module_title);
Console.WriteLine("Score: " + m.module_mark);
}
}

Related

How can I sort an object array in C# based on user input?

I have an array that is populated with user input and needs to be sorted according to a particular property. I have looked at similar questions on here but it does not seem to help my specific situation and so far nothing I've tried has worked.
The properties for the array are defined in a separate class.
It's a basic program for loading employees onto a system and the output needs to be sorted according to their salary.
*Note that I am a student and I am possibly missing something very basic.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
namespace Instantiating_Objects
{
class Program
{
static void Main(string[] args)
{
//Cleaner cleaner = new Cleaner(); // Instantiantion
// Object Array
Cleaner[] clean = new Cleaner[3]; // Empty Object Array
Cleaner[] loadedCleaners = LoadCleaners(clean);
for (int i = 0; i < loadedCleaners.Length; i++)
{
Console.WriteLine(" ");
Console.WriteLine(loadedCleaners[i].Display() + "\n Salary: R" + loadedCleaners[i].CalcSalary());
}
Console.ReadKey();
}
public static Cleaner[] LoadCleaners(Cleaner[] cleaner)
{
for (int i = 0; i < cleaner.Length; i++)
{
Console.WriteLine("Enter your staff number");
long id = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Enter your last name");
string lname = Console.ReadLine();
Console.WriteLine("Enter your first name");
string fname = Console.ReadLine();
Console.WriteLine("Enter your contact number");
int contact = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your number of hours worked");
int hours = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
// Populating object array
cleaner[i] = new Cleaner(id, fname, lname, contact, hours);
}
Array.Sort(, )
return cleaner;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Instantiating_Objects
{
class Cleaner
{
private long staffNo;
private string lastName;
private string fName;
private int contact;
private int noHours;
private double rate = 380.00;
public Cleaner() { }
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
this.contact = number;
this.fName = surname;
this.lastName = name;
this.staffNo = staffId;
this.noHours = hours;
}
public int GetHours() { return noHours;}
public long GetStaffID() { return staffNo; }
public string GetSurname() { return lastName; }
public string GetName() { return fName; }
public int GetNumber() { return contact; }
// Calculate Salary
public double CalcSalary()
{
double salary = 0;
if(GetHours() > 0 && GetHours() <= 50)
{
salary = GetHours() * rate;
}
else if (GetHours() > 50)
{
salary = (GetHours() * rate) + 5000;
}
return salary;
}
public string Display()
{
return "\n Staff no: " + GetStaffID() + "\n Surname" + GetSurname()
+ "\n Name: " + GetName() + "\n Contact no: " + GetNumber();
}
}
}
I will combine Legacy code and Ňɏssa Pøngjǣrdenlarp into one.
First thing as Ňɏssa Pøngjǣrdenlarp said your Cleaner class has no properties.
I removed all your methods and changed it with properties instead
public class Cleaner
{
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
StaffNo = staffId;
FName = name;
LastName = surname;
Contact = number;
NoHours = hours;
}
public long StaffNo { get; set; }
public string LastName { get; set; }
public string FName { get; set; }
public int Contact { get; set; }
public int NoHours { get; set; }
public double Rate => 380.00;
public double Salary
{
get
{
double salary = 0;
if (NoHours > 0 && NoHours <= 50)
{
salary = NoHours * Rate;
}
else if (NoHours > 50)
{
salary = (NoHours * Rate) + 5000;
}
return salary;
}
}
public override string ToString()
{
return "\n Staff no: " + StaffNo + "\n Surname" + LastName
+ "\n Name: " + FName + "\n Contact no: " + Contact;
}
}
Now that we have fixed the class we can look at the Program Main method.
Because we changed the cleaner class to use properties instead we can easily use Linq to orderby
private static void Main(string[] args)
{
//Cleaner cleaner = new Cleaner(); // Instantiantion
// Object Array
var clean = new Cleaner[3]; // Empty Object Array
var loadedCleaners = LoadCleaners(clean).OrderBy(_ => _.Salary).ToArray();
foreach (Cleaner v in loadedCleaners)
{
Console.WriteLine(" ");
Console.WriteLine(v + "\n Salary: R" + v.Salary);
}
Console.ReadKey();
}
You will notice that on this line
var loadedCleaners = LoadCleaners(clean).OrderBy(_ => _.Salary).ToArray();
that i am using Linq to order the Salary.
For more on Linq check out the following docs https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
On a side note
I would say consistency is key, this will keep your code clean.
Look at the following example, the naming convention is inconsistent
public Cleaner(long staffId, string name, string surname, int number, int hours)
{
StaffNo = staffId;
FName = name;
LastName = surname;
Contact = number;
NoHours = hours;
}
Nice, clean and easy to follow
public Cleaner(long staffId, string firstName, string lastName, int number, int hours)
{
StaffId = staffId;
FirstName = firstName;
LastName = lastName;
Number = number;
Hours = hours;
}

Need help in C# to delete obj in a list

I have an employee management system which I'm trying to build in c# console application whereas im able to add a new employee.
but I'm not sure on how can I delete a employee from the list.
I have to put together both method then it works.
it seem like i'm unable to call the obj (emp) from my removeEmployee method
Main class
using System;
namespace HRM
{
class Program
{
static void Main(string[] args)
{
manageEmp emp = new manageEmp();
emp.addEmployee();
emp.removeEmployee();
}
}
}
Employee Class
using System;
using System.Collections.Generic;
namespace HRM
{
public class Employee
{
private String empID;
private String empFirstName;
private String empLastName;
private String empDep;
private String empDOB;
private String empAddress;
private int PostalCode;
private double empSal;
public Employee()
{
}
public Employee(String aempID, string aempFirstName, string aempLasttName, string aempDep, String aEmpDOB, string aempAddress, int aPostalCode, double aempSal)
{
this.EmpID = aempID;
this.EmpFirstName = aempFirstName;
this.EmpLastName = aempLasttName;
this.EmpDep = aempDep;
this.EmpDOB = aEmpDOB;
this.EmpAddress = aempAddress;
this.PostalCode1 = aPostalCode;
this.EmpSal = aempSal;
}
public string EmpID { get => empID; set => empID = value; }
public string EmpFirstName { get => empFirstName; set => empFirstName = value; }
public string EmpLastName { get => empLastName; set => empLastName = value; }
public string EmpDep { get => empDep; set => empDep = value; }
public string EmpDOB { get => empDOB; set => empDOB = value; }
public string EmpAddress { get => empAddress; set => empAddress = value; }
public int PostalCode1 { get => PostalCode; set => PostalCode = value; }
public double EmpSal { get => empSal; set => empSal = value; }
public List<Employee> El { get => el; set => el = value; }
public override string ToString()
{
return "Employment ID : " + empID + "\n"
+ "FirstName : " + EmpFirstName + "\n"
+ "LastName : " + EmpLastName + "\n"
+ "Department : " + EmpDep + "\n"
+ "Date of Birth: " + EmpDOB + "\n"
+ "Address : " + EmpAddress + "\n"
+ "PostalCode : " + PostalCode1 + "\n"
+ "empSal : " + EmpSal + "\n";
}
}
}
manageEmp class
using System;
using System.Collections.Generic;
namespace HRM
{
public class manageEmp
{
private List<Employee> el = new List<Employee>();
public List<Employee> El { get => el; set => el = value; }
public void addEmployee()
{
Console.WriteLine("===================================" + "\n");
Console.WriteLine("Add an Employee");
Console.WriteLine("===================================" + "\n");
Console.WriteLine("");
Console.WriteLine("Please enter your Employment ID");
String eID = Console.ReadLine();
Console.WriteLine("Please enter your First Name");
String eFirstName = Console.ReadLine();
Console.WriteLine("Please enter your Last Name");
String eLasttName = Console.ReadLine();
Console.WriteLine("Please entter your department");
String eDep = Console.ReadLine();
Console.WriteLine("Please enter your Date of Birth");
String eDOB = Console.ReadLine();
Console.WriteLine("Please entter your Address");
String eAddress = Console.ReadLine();
Console.WriteLine("Please enter your Postal Code");
int ePostalCode = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter your Salary");
double eSal = Convert.ToDouble(Console.ReadLine());
Employee emp = new Employee(eID, eFirstName, eLasttName, eDep, eDOB, eAddress, ePostalCode, eSal);
emp.El.Add(emp);
}
public void viewEmployee()
{
Employee nemp = new Employee();
nemp.El.ForEach(Console.WriteLine);
}
public void removeEmployee()
{
Console.WriteLine("Please enter a employee Id to be deleted");
String delemp = Console.ReadLine();
for (int i = 0; i < El.Count; i++)
{
emp = El[i];
if (delemp.Equals(eID))
{
el.Remove(emp);
}
Console.WriteLine(delemp + " Has been deleted sucessfully");
el.ForEach(Console.WriteLine);
}
}
}
}
Your problem is that your employee list is inside the employee class -- so each of the employees has its own list of employees -- and that list only contains that single employee.
In the function RemoveEmployee you are creating a new manageEmp object. As the word 'new' implies, this is a different, newly created manageEmp with its own, newly created List<Employee> which doesn't contain any items.
Further, you have declared the function as public void removeEmployee(string eID) so you can't call it with the line emp.removeEmployee().

C# Basic OOP - Making a Dictionary of a Class with Constructors

The code I've been trying and what went wrong: http://ideone.com/cvLRLg
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Minion
{
public static int manaCost;
public static int attack;
public static int health;
public static string cardText;
public Minion(int mana, int atk, int h, string txt)
{
manaCost = mana;
attack = atk;
health = h;
cardText = txt;
}
public void displayStats(string name)
{
Console.WriteLine(name + "\nMana Cost: " + manaCost + "\nAttack: " + attack + "\nHealth: " + health + "\n" + cardText + "\n");
}
}
class Program
{
static void Main(string[] args)
{
List<string> indexList = new List<string>();
Dictionary<string, Minion> minionList = new Dictionary<string, Minion>();
//buffer so I start at 1 and not 0
indexList.Add("MissingNo");
//make a Wolfrider card
indexList.Add("Wolfrider");
Minion Wolfrider = new Minion(3, 3, 1, "Charge");
minionList.Add(indexList[1], Wolfrider);
//make a Goldshire Footman card
indexList.Add("Goldshire Footman");
Minion GoldshireFootman = new Minion(1, 1, 2, "Taunt");
minionList.Add(indexList[2], GoldshireFootman);
//look through all my cards
for (int i = 1; i < indexList.Count(); i++)
minionList[indexList[i]].displayStats(indexList[i]);
Console.ReadLine();
}
}
}
I have been trying to teach myself C# but this has been stumping me. I want to make a Dictionary that accepts a string then returns a Minion (the new class).
A Minion accepts four arguments when it's made so I had to dedicate a line of code to making a new Minion BEFORE adding that to the Dictionary.
However, when I'm going through all the Minions that I have, for some reason the first one is giving me back the properties of the OTHER Minion.
Wolfrider
Mana Cost: 1
Attack: 1
Health: 2
Taunt
Goldshire Footman
Mana Cost: 1
Attack: 1
Health: 2
Taunt
The List is working properly because the names are correct... but the Wolfrider has the properties of the Goldshire Footman.
Is there a more efficient/optimized way to do this? If not, what have I been doing wrong?
The main issue is that your members are static:
public static int manaCost
So basically, the last value you affect wins. Transform them into instance properties:
public int ManaCost { get; set; }
Then get rid of indexList and directly use your Minion's name as the dictionary key.
Well remove keyword static from all your class members. You don't want for all minions to have same values don't you ?
You can also add field or property name to your class :
public class Minion
{
public readonly string name;
public int manaCost;
public int attack;
public int health;
public string cardText;
public Minion(string name, int mana, int atk, int h, string txt)
{
this.name = name;
this.manaCost = mana;
this.attack = atk;
this.health = h;
this.cardText = txt;
}
public void displayStats()
{
Console.WriteLine(name + "\nMana Cost: " + manaCost + "\nAttack: " + attack + "\nHealth: " + health + "\n" + cardText + "\n");
}
}
In your Main method you don't really need this List<string> to work with your dictionary. You can remove it and change your code to :
Dictionary<string, Minion> minionList = new Dictionary<string, Minion>();
Minion Wolfrider = new Minion("Wolfrider", 3, 3, 1, "Charge");
minionList.Add(Wolfrider.name , Wolfrider);
//make a Goldshire Footman card
Minion GoldshireFootman = new Minion("Goldshire", 1, 1, 2, "Taunt");
minionList.Add(GoldshireFootman.name, GoldshireFootman);
foreach(Minion minion in minionList.Values)
minion.DisplayStats();
Console.ReadLine();
You should not have static members for your class. Remove the static in the below.
public static int manaCost;
public static int attack;
public static int health;
public static string cardText;
Here is a slightly cleaner version of what you may be aiming for:
using System;
using System.Collections.Generic;
namespace ConsoleApplication3
{
public class Minion
{
public string name { get; set; }
public int manaCost { get; set; }
public int attack { get; set; }
public int health { get; set; }
public string cardText { get; set; }
public void displayStats()
{
Console.WriteLine(name + "\nMana Cost: " + manaCost + "\nAttack: " + attack + "\nHealth: " + health + "\n" + cardText + "\n");
}
class Program
{
static void Main(string[] args)
{
var minionList = new List<Minion>();
minionList.Add(new Minion() { name = "Wolfrider", attack = 3, cardText = "Charge", health = 3, manaCost = 3 });
minionList.Add(new Minion() { name = "GoldShire Footman", attack = 1, cardText = "Taunt", health = 1, manaCost = 2 });
//look through all my cards
foreach (var minion in minionList)
minion.displayStats();
Console.ReadLine();
}
}
}
}

How do I populate a string array upon instantiation?

So I have created a class that holds properties for the names of albums, including their genre, name and artist with an array that will hold the track list. When compiled, the properties' default values are replaced however I don't know how to replace the default values for the array - I don't know how to replace the default track listing with new tracks for each album. Thanks.
Here is the CD.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_2
{
class Cd
{
string name;
string artist;
string genre;
public string[] tracklist;
public string[] newTracklist;
public string getName()
{
return name;
}
public void setName(string newName)
{
name = newName;
}
public string getArtist()
{
return artist;
}
public void setArtist(string newArtist)
{
artist = newArtist;
}
public string getGenre()
{
return genre;
}
public void setGenre(string newGenre)
{
genre = newGenre;
}
public string[] getTracklist()
{
return tracklist;
}
public void setTracklist(string[] newTracklist)
{
string[] tracklist = newTracklist;
}
public Cd()
{
this.name = "CD Name";
this.artist = "CD Artist";
this.genre = "CD Genre";
this.tracklist = new string[3] { "Track1", "Track2", "Track3" };
this.newTracklist = new string[3] { "newTrack1", "newTrack2", "newTrack3" };
}
}
}
And here is the main.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercise_2
{
class Exercise2
{
static void Main()
{
Cd CD1 = new Cd();
CD1.setName("Kill 'Em All");
CD1.setArtist("Metallica");
CD1.setGenre("Thrash Metal");
Cd CD2 = new Cd();
CD2.setName("Ride The Lightning");
CD2.setArtist("Metallica");
CD2.setGenre("Thrash Metal");
Cd CD3 = new Cd();
CD3.setName("Master Of Puppets");
CD3.setArtist("Metallica");
CD3.setGenre("Thrash Metal");
Console.WriteLine(CD1.getName() + " - " + CD1.getArtist() + " - " + CD1.getGenre() + " - " + CD1.getTracklist());
Console.WriteLine(CD2.getName() + " - " + CD2.getArtist() + " - " + CD2.getGenre());
Console.WriteLine(CD3.getName() + " - " + CD3.getArtist() + " - " + CD3.getGenre());
}
}
}
The problem is your setTracklist method creates a new array every time:
public void setTracklist(string[] newTracklist)
{
string[] tracklist = newTracklist;
}
Instead, you need to set the instance tracklist member:
public void setTracklist(string[] newTracklist)
{
tracklist = newTracklist;
}
One more piece of advice. Don't create methods to get and set properties, it's just unnecessary work. Change:
string name;
string artist;
string genre;
public string[] tracklist;
public string[] newTracklist;
To:
public string Name {get; set;}
public string Artist {get; set;}
public string Genre {get; set;}
public string[] Tracklist {get; set;}
You also might want to change tracklist to a List<String> so you can easily add tracks:
public List<String> Tracklist {get; set;}
If you do this, you can create a Cd instance a lot easier:
var newCD = new Cd
{
Name = "Kill 'Em All",
Artist = "Metallica",
Genre = "Thrash Metal"
};
newCD.Tracklist.Add("Hit the Lights");
newCD.Tracklist.Add("The Four Horsemen");
newCD.Tracklist.Add("Motorbreath");
// etc etc
Update:
Here's the full code, in case something got mixed up. I've also implemented a getTracklist method which returns all the tracks is a comma delimited form.
using System;
using System.Collections.Generic;
class Cd
{
public string Name { get; set; }
public string Artist { get; set; }
public string Genre { get; set; }
public List<string> Tracklist { get; set; }
public Cd()
{
Name = "CD Name";
Artist = "CD Artist";
Genre = "CD Genre";
Tracklist = new List<string>();
}
public string getTracklist()
{
return String.Join(", ", Tracklist);
}
}
public class Exercise2
{
public static void Main()
{
Cd CD1 = new Cd();
CD1.Name = "Kill 'Em All";
CD1.Artist = "Metallica";
CD1.Genre = "Thrash Metal";
CD1.Tracklist.Add("Hit the Lights");
CD1.Tracklist.Add("The Four Horsemen");
CD1.Tracklist.Add("Motorbreath");
Cd CD2 = new Cd();
CD2.Name = "Ride The Lightning";
CD2.Artist = "Metallica";
CD2.Genre = "Thrash Metal";
Cd CD3 = new Cd();
CD3.Name = "Master Of Puppets";
CD3.Artist = "Metallica";
CD3.Genre = "Thrash Metal";
Console.WriteLine(CD1.Name + " - " + CD1.Artist + " - " + CD1.Genre + " - " + CD1.getTracklist());
Console.WriteLine(CD2.Name + " - " + CD2.Artist + " - " + CD2.Genre);
Console.WriteLine(CD3.Name + " - " + CD3.Artist + " - " + CD3.Genre);
}
}
You would just write
CD1.setTrackList(new string[] {"Hit The Lights", "The Four Horsemen", "Motorbreath"});
And your setTrackList should read:
public void setTracklist(string[] newTracklist)
{
tracklist = newTracklist;
}
The way you originally wrote it, you were creating a new array of tracks each time you were setting it, instead of setting the backing property.
However, there is a better way to do this. C# has what's called Auto Properties. They handle all this for you.
public string Name {get; set;}
public string Artist {get; set;}
//.... etc

How to take in user input and print out details

I'm working on an exam app (c# console application)
The app asks the user to enter its name, I would like the app to read in that user's name and
print the user's details based on the details I've stored in the objects
For example:
If the user's name matches the name in this object:
students s3 = new students("Dee", "Scott", "Computing", 100m, 66.6m);
how could it print this user's details.
I've got a separate method that prints out the user's details
public string gradeDetails {
get { return FirstName + LastName + Course + FinalGrade; }
}
I cant figure out how to match the user input to corresponding object.
You can use the Console.Readline() method
public static void Main()
{
string line;
Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit):");
Console.WriteLine();
do {
Console.Write(" ");
line = Console.ReadLine();
if (line != null)
Console.WriteLine(" " + line);
} while (line != null);
Console.ReadLine();
Console.WriteLine(); or Console.Write();
I am not sure if that is what you are asking, but those are the calls to read and write.
This info is easily Google-able though.
The example below will do what you asked for. If you have any questions regarding the code I used then don't hesitate to ask.
class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Course { get; set; }
public decimal FinalGrade { get; set; }
public Student(string firstName,
string lastName,
string course)
{
FirstName = firstName;
LastName = lastName;
Course = course;
FinalGrade = 0;
}
// This will first call the constructor above and then continue.
public Student(string firstName,
string lastName,
string course,
decimal finalGrade) : this(firstName, lastName, course)
{
FinalGrade = finalGrade;
}
// By overriding ToString we can use Console.WriteLine(student) directly.
public override string ToString()
{
return string.Format(#"FirstName: {0}, LastName: {1}, Course: {2}, FinalGrade: {3}",
FirstName,
LastName,
Course,
FinalGrade);
}
}
class Program
{
static void Main(string[] args)
{
// Create our students.
List<Student> students = new List<Student>
{
new Student("John", "Test", "Computing"),
new Student("Tim", "Test", "Computing", 8.25m)
};
string user = "";
do
{
Console.Clear();
Console.WriteLine("Please enter the name of the student:");
user = Console.ReadLine();
if (user.Equals("exit", StringComparison.OrdinalIgnoreCase))
break;
// Find the student or return null.
Student student = students.FirstOrDefault(s => s.FirstName.Equals(user, StringComparison.OrdinalIgnoreCase));
if (student != null)
{
Console.WriteLine("Student info:");
Console.WriteLine(student);
}
else
{
Console.WriteLine("Student '" + user + "' not found.");
}
Console.WriteLine();
// Wait until a key is pressed.
Console.WriteLine("Press a key to continue..");
Console.ReadKey(true);
} while (true);
}
}
Do something like this:
create a class called Student:
public class Student
{
public string Fname { get; set; }
public string LName { get; set; }
public string Course { get; set; }
public string FinalGrade { get; set; }
}
Then do this
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter you name:");
string name = Console.ReadLine();
Console.WriteLine(gradeDetails(name));
Console.ReadLine();
}
public static string gradeDetails(string name)
{
List<Student> students = new List<Student>()
{
new Student{ Fname = "Scott",LName ="Dee",Course = "Computing", FinalGrade = "66.66m"},
new Student{Fname = "Joe",LName = "Don",Course = "Chemestry", FinalGrade = "80.77m"}
};
var student = students.SingleOrDefault(s => s.LName.ToLower() == name.ToLower());
if (student!=null)
{
return student.Fname + "" + student.LName + "" + student.Course + "" + student.FinalGrade;
}
return string.Empty;
}
}
Ask user to enter name and print name
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace stackoverflow1
{
class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("Enter your name : ");
name = Console.ReadLine();
Console.WriteLine("Hello " + name + " , Welcome to OOP!");
Console.ReadKey();
}
}
}

Categories