I'm trying to return multiple parameters, if that's how to word it. I'm trying to "translate" Python code into C#.
I'm actually not quite sure what exact term I'm searching for, but I know how to do it in Python so I'll just show my code.
class Staff
{
public String name;
public int age;
/* Now in Python, you can easily write this following, but I have no
idea how this works in C#. I basically want to return all the values
for each employee in the "Staff" class */
def desc(self):
desc_str = "%s is %s years old." % (self.name, self.age)
return desc_str
}
class Program
{
public static void Main()
{
Staff Jack = new Staff();
Jack.name = "Jack";
Jack.age = 40;
Staff Jill = new Staff();
Jill.name = "Jill";
Jill.age = 50;
Console.WriteLine(Jack.desc());
Console.WriteLine(Jill.desc());
Console.ReadKey();
}
}
EDIT: I figured out that what I was searching for was get, set and ToString() and will look into it now.
The code I've translated looks like the following now:
class Staff
{
private string name;
private int age;
private string yearsold = " years old.";
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public string YearsOld
{
get
{
return yearsold;
}
set
{
yearsold = value;
}
}
public override string ToString()
{
return "Employee " + Name + " is " + Age + YearsOld;
}
}
class TestPerson
{
static void Main()
{
// Create a new Person object:
Staff person = new Staff();
person.Name = "Jack";
person.Age = 40;
Console.WriteLine(person);
person.Name = "Jill";
person.Age = 50;
Console.WriteLine(person);
Console.ReadKey();
}
}
Since you have a class, you can override the ToString function and use the string.Format function like so:
class Staff
{
public string name;
public int age;
public Staff(string _name, int _age)
{
this.name = _name;
this.age = _age;
}
public override string ToString()
{
return string.Format("{0} is {1} years old.", this.name, this.age);
}
}
Then to print:
Staff Jack = new Staff("Jack", 40);
Console.WriteLine(Jack); // implicitly calls Jack.ToString()
Hope that helps.
Related
The code is for taking the input from user such as their name and date of birth and return details as name and their age and whether they are child or not
Apart from the Adult property the rest of the code works fine
using System;
using System.IO;
public class Person
{
//Fill code here
private string firstName;
private string lastName;
private DateTime dob;
//private string adult;
public string FirstName
{
set { firstName = value; }
get { return firstName; }
}
public string LastName
{
set { lastName = value; }
get { return lastName; }
}
public DateTime Dob
{
set { dob = value; }
get { return dob; }
}
}
In the below property it has to check age and return "Adult" if the age is above or equal to 18 else "Child".
And according to the question i cannot declare the field for this.
public string Adult
{
get
{
return Adult;
throw (stackoverflow)
}
set
{
if (GetAge(dob) >= 18)
{
Adult = "Adult";
}
else
{
Adult = "Child";
}
}
}
Help me with the corrections needed for the above property so that it does not throw any exceptions and the reason why it throws the exception
public void DisplayDetails()
{
Console.WriteLine("First Name: {0}", firstName);
Console.WriteLine("Last Name: {0}", lastName);
int age = GetAge(dob);
Console.WriteLine("Age: {0}",age);
Console.WriteLine(Adult);
}
public int GetAge(DateTime dob)
{
int age = 0;
age = DateTime.Now.Year - dob.Year;
return age;
}
}
public class Program
{
public static void Main(String[] args)
{
//Fill code here
Person p = new Person();
Console.WriteLine("Enter first name");
p.FirstName = Console.ReadLine();
Console.WriteLine("Enter last name");
p.LastName = Console.ReadLine();
Console.WriteLine("Enter date of birth in yyyy/mm/dd/ format");
p.Dob = Convert.ToDateTime(Console.ReadLine());
p.DisplayDetails();
}
}
You have an Adult property, and inside that property you manually defined a getter and setter, but they both use exactly the same property instead of using a field like you do in your other properties.
Note that the fields used in your other properties have lowercase names, while the properties start with an Upper case letter (which means that they are separate entities).
So you did declare adult like this but have commented it out:
//private string adult;
So you need to first uncomment it, then use it in your getter & setter.
public string Adult
{
get
{
return adult;
}
set
{
if (GetAge(dob) >= 18)
{
adult = "Adult";
}
else
{
adult = "Child";
}
}
}
But this also doesn't make sense, as your setter is not using the value which you pass into it! So while this might work, it is not really the best way to do it. Instead just use the Getter to return if it is an adult or child each time.
public string Adult
{
get
{
if (GetAge(dob) >= 18)
return "Adult";
else
return "Child";
}
}
(You should also include handling in case dob value is not valid (e.g. default value)
BTW: It might be better to use an Enum rather than a string, or just a boolean indicating if it is an adult (true) or child (false).
My professor wants us to create a reusable class and console app that lists book objects. I got the first part of the assignment where I am supposed to print the books I created, but now I am stuck on the part where I have to modify the data and print again using the same method and then check out two books and print again. I have tried to look at example online and although some of them have helped, none have been able to get me to pass this roadblock.
class LibraryBook
{
private string _bookTitle;
private string _authorName;
private string _publisher;
private int _copyrightYear;
private string _callNumber;
public LibraryBook(string booktitle, string authorname, string publisher, int ccyear, string callnumber)
{
BookTitle = booktitle;
AuthorName = authorname;
Publisher = publisher;
CopyrightYear = ccyear;
CallNumber = callnumber;
}
public string BookTitle
{
get
{
return _bookTitle;
}
set
{
_bookTitle = value;
}
}
public string AuthorName
{
get
{
return _authorName;
}
set
{
_authorName = value;
}
}
public string Publisher
{
get
{
return _publisher;
}
set
{
_publisher = value;
}
}
public int CopyrightYear
{
get
{
return _copyrightYear;
}
set
{
const int CYEAR = 2019;
if (value > 0)
_copyrightYear = value;
else
_copyrightYear = CYEAR;
}
}
public string CallNumber
{
get
{
return _callNumber;
}
set
{
_callNumber = value;
}
}
public bool Avail;
public void CheckOut()
{
Avail = true;
}
public void ReturnToShelf()
{
Avail = false;
}
public bool IsCheckedOut()
{
return Avail;
}
public override string ToString()
{
return $"Book Title: {BookTitle}{Environment.NewLine}" +
$"Author Name: {AuthorName}{Environment.NewLine}" +
$"Publisher: {Publisher}{Environment.NewLine}" +
$"Copyright Year: {CopyrightYear}{Environment.NewLine}" +
$"Call Number: {CallNumber}{Environment.NewLine}" +
$"Checked Out: {IsCheckedOut()}{Environment.NewLine}";
}
}
}
class Program
{
static void Main(string[] args)
{
LibraryBook[] favBooksArray = new LibraryBook[5];
favBooksArray[0] = new LibraryBook("Harry Potter and the Philospher's Stone", "J.K. Rowling", "Scholastic Corporation", 1997, "HA-12.36");
favBooksArray[1] = new LibraryBook("Harry Potter and the Chamber of Secret", "J.K. Rowling", "Scholastic Corporation", 2001, "HA-13.48");
favBooksArray[2] = new LibraryBook("Tangerine", "Edward Bloor", "Harcourt", 1997, "TB-58.13");
favBooksArray[3] = new LibraryBook("Roll of Thunder, Hear My Cry", "Mildred D. Taylor", "Dial Press", 1976, "RT-15.22");
favBooksArray[4] = new LibraryBook("The Giver", "Lois Lowry", "Fake Publisher", -1, "Fk200-1");
WriteLine($"------LIBRARY BOOKS------{Environment.NewLine}");
BooksToConsole(favBooksArray);
WriteLine($"------CHANGES MADE----- {Environment.NewLine}");
ChangesToBooks(favBooksArray);
BooksToConsole(favBooksArray);
WriteLine($"------RETURNING BOOKS TO SHELF------{Environment.NewLine}");
ReturnBooksToConsole(favBooksArray);
BooksToConsole(favBooksArray);
}
public static void BooksToConsole(LibraryBook[] favBooksArray)
{
foreach (LibraryBook books in favBooksArray)
{
WriteLine($"{books}{Environment.NewLine}");
}
}
public static void ChangesToBooks(LibraryBook[] favBooksArray)
{
favBooksArray[1].AuthorName = "*****The Rock*****";
favBooksArray[3].BookTitle = "****Totally Not A Fake Name*****";
favBooksArray[1].CheckOut();
favBooksArray[4].CheckOut();
}
public static void ReturnBooksToConsole(LibraryBook[] favBooksArray)
{
favBooksArray[1].ReturnToShelf();
favBooksArray[4].ReturnToShelf();
}
}
}
When I run this program in Main() it keep giving me error messages saying that "Tommy", "Bulldog", and "Male" don't exist in current context. I couldn't figure out why? The program was running fine until I add those strings. Can anyone help me understand?
namespace indexusingthismethod
{
public class Dog
{
private string name;
private string breed;
private string gender;
public Dog()
{
name = "Fido";
breed = "Mongrel";
gender = "Male";
}
public Dog(string dogName, string dogBreed, string dogGender)
{
name = dogName;
breed = dogBreed;
gender = dogGender;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Breed
{
get { return breed; }
set { breed = value; }
}
public string Gender
{
get { return gender; }
set { gender = value; }
}
public string this[int index]
{
set
{
switch (index)
{
case 0: name = value;
break;
case 1: breed = value;
break;
case 2: gender = value;
break;
default: throw new ArgumentOutOfRangeException("index");
}
}
get
{
switch (index)
{
case 0: return name;
case 1: return breed;
case 2: return gender;
default: throw new ArgumentOutOfRangeException("index");
}
}
}
public void Bark()
{
Console.WriteLine("{0} said: Woof!", name);
}
}
public class Doggies
{
static void Main()
{
Dog descriptionofDog = new Dog();
Console.WriteLine("Dog name: {0}\nDog breed: {1}\nDog gender: {2}\n", descriptionofDog [0], descriptionofDog [1],
descriptionofDog [2]);
descriptionofDog[0] = Tommy;
descriptionofDog[1] = Bulldog;
descriptionofDog[2] = Male;
Console.WriteLine("Dog name: {0}\nDog breed: {1}\nDog gender: {2}\n",descriptionofDog[0], descriptionofDog[1],
descriptionofDog[2]);
Dog has 3 string properties on it. Name, Breed and Gender.
When you built up the descriptionofDog object, you left off the quotes which told the compiler that these are objects, not strings.
Just put quotes around your string literals:
descriptionofDog[0] = "Tommy";
descriptionofDog[1] = "Bulldog";
descriptionofDog[2] = "Male";
To add to the #paq...'s answer. Following are the easier way to create new Dog object instead of using indexer.
Dog descriptionofDog = new Dog();
or
descriptionofDog = new Dog("Tommy", "Bulldog", "Male");
or
descriptionofDog =
new Dog() { Name = "Tommy", Breed = "Bulldog", Gender = "Male" };
I'm trying to figure out how to populate an array with an object with multiple variables. What I need is to create an array, not a list(I'm trying to learn arrays), and populate it with 5 different bourbons. Is it possible to populate the array and store the name, age, distillery in just one index? For example,
If I called index 0, it would display:
Name: Black Maple Hill
Distillery: CVI Brands, Inc
Age: 8 years
I have this so far, in which bourbon is a derived class from whiskey and call a method in the main class to prompt user for entry.
class Bourbon : Whiskey
{
private Bourbon[] bBottles = new Bourbon[5];
public void bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs ++)
{
}
}
}
In your code you haven't defined the value variable that you are using inside the for loop. You could create new instances of the class and then store them inside the array:
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs ++)
{
Console.WriteLine("Name:");
var name = Console.ReadLine();
Console.WriteLine("Distillery:");
var distillery = Console.ReadLine();
Console.WriteLine("Age:");
var age = int.Parse(Console.ReadLine());
var bourbon = new Bourbon(name, distillery, age);
bBottles[runs] = bourbon;
}
}
Also make sure you have defined the Bourbon class constructor properly:
public Bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}
#Jonathan. Yes, it is possible, based on my interpretation. You can try making use of indexers.
Class Bourbon : Whiskey {
public Bourbon this[int index]
{
get {
return bBottles[index];
}
set {
bBottles[index] = value;
}
}
}
Check this Need to Create Property and One Constructor to achieve your requirement.
class Bourbon
{
private Bourbon[] bBottles = new Bourbon[5];
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string distillery;
public string Distillery
{
get { return distillery; }
set { distillery = value; }
}
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public Bourbon(string name, string distillery, int age)
{
Name = name;
Distillery = distillery;
Age = age;
}
public void PopulateBottles()
{
Console.WriteLine("Please enter the information for 5 bourbons:");
for (int runs = 0; runs < 5; runs++)
{
Console.WriteLine("Name:");
var name = Console.ReadLine();
Console.WriteLine("Distillery:");
var distillery = Console.ReadLine();
Console.WriteLine("Age:");
var age = int.Parse(Console.ReadLine());
var bourbon = new Bourbon(name, distillery, age);
bBottles[runs] = bourbon;
}
}
}
In my program I have a list of marks and a dictionary which stores the studentId. I want that the user enters the studentId and according to that id it will point to the list of marks. I think I am implementing it incorrectly. Can someone help me in implementing it. Thanks
public class Student() {
private string name;
private string surname;
private string dob;
private string address;
private int id;
public Student()
{
}
public Student(string year,string name, string surname, string dob, string address)
{
this.name = name;
this.surname = surname;
this.dob = dob;
this.address = address;
this.year = year;
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Surname
{
get { return surname; }
set { surname = value; }
}
public string DOB
{
get { return dob; }
set { dob = value; }
}
public string Addr
{
get { return address; }
set { address = value; }
}
public int Id
{
get { return id; }
set { id = value; }
}
private string year;
public string Year
{
get { return year; }
set { year = value; }
}
public Student(string s)
{
string[] splitted = s.Split(',');
name = splitted[0];
surname = splitted[1];
dob = splitted[2];
address = splitted[3];
// id = splitted[4];
}
public Dictionary<int,List<Marks>> dictionary= new Dictionary<int,List<Marks>>();
public List<Marks> Mathematics = new List<Marks>();
public List<Marks> English = new List<Marks>();
public List<Marks> Maltese = new List<Marks>();
public List<Marks> ReligiousStudies = new List<Marks>();
public List<Marks> SocialStudies = new List<Marks>();
public Dictionary<int, List<Marks>> dictionar = new Dictionary<int, List<Marks>>();
public void AddMarks(int hyexam, int anexam)
{
{
Console.WriteLine("enter id of student to input marks to:");
string id = Console.ReadLine();
if (dictionar.ContainsKey(Id).Equals(id))
{
Mathematics.Add(new Marks(hyexam, anexam));
English.Add(new Marks(hyexam, anexam));
Maltese.Add(new Marks(hyexam, anexam));
ReligiousStudies.Add(new Marks(hyexam, anexam));
SocialStudies.Add(new Marks(hyexam, anexam));
dictionar.Add(id, (Mathematics)); //dont know how to implement it
}
else
{
Console.WriteLine("id not found");
}
}
}
public class Marks
{
private int hyexam;
private int anexam;
private string id;
public int HYEXAM
{
get { return hyexam; }
set { hyexam = value; }
}
public int ANEXAM
{
get { return anexam; }
set { anexam = value; }
}
public string Id
{
get { return id; }
set { id = value; }
}
public Marks(int hyexam, int anexam)
{
this.hyexam = hyexam;
this.anexam = anexam;
}
public Marks(string id)
{
this.id = id;
}
public double OverallExam()
{
return (0.4 * hyexam) + (0.6 * anexam);
}
}
}
I'd say the main problem is your modelling. You've included the Dictionary<int, List<Marks>> as a field within Student. That means that each Student object has a dictionary. That makes no sense - because the key for the dictionary is meant to be the student ID, right?
It probably makes sense for each Student object to the lists of marks as you've currently got (although not as public fields, IMO). Given that information, do you really need a Dictionary going to the marks at all? Wouldn't it be cleaner to have a Dictionary<int, Student> somewhere (not in the Student class - maybe in a School class?) mapping each student ID to a Student, and you can get the marks from the Student?
Think hard about what you're trying to achieve, and where the data really belongs. In my experience, when you've got the data modelling right, the code usually follows in a clean way.
(I'd also question your Marks class, both in terms of name and design. What are those properties meant to represent? Isn't it really a single mark in an exam? Perhaps ExamResult would be clearer? Does it really need to be mutable?)
I'd agree with Jon that this is definitely a modeling issue (based on the OP's other posts). If you're new to object oriented programming, the first thing you need to do is determine what objects you'll need to create to answer the problem.
What is a Student? A student has a name, id, dob, class year, etc. For every attribute a student has, you need to set up a field or property.
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime DoB { get; set; }
... etc ...
}
What is a Mark? From your descriptions, a Mark has a subject, a mid-exam score, and an annual-exam score.
public class Mark
{
public string Subject { get; set; }
public int MidScore { get; set; }
public int FinalScore { get; set; }
}
What is the relationship between a Student and a Mark? A student has a list of marks associated with them. This is best described with a List<> object.
public class Student() // continued
{
public List<Mark> Marks { get; set; }
}
Once you have the basics set up for your objects, it will be easier to filter out what you DON'T need, and make it much easier to answer your question. :)
My proposal:
Your "Mark" class must have something that identifies the subject (could be an enum called Subject, or an string, or an int with the ID of the subject if you have it stored in database)
Then you could have:
Console.WriteLine("enter id of student to input marks to:");
string id = Console.ReadLine();
var marks = new Dictionary<int, List<Mark>>();
if (UserExists(id))
{
Console.WriteLine("mark for subject1:");
string s1 = Console.ReadLine();
Console.WriteLine("mark for subject2:");
string s2 = Console.ReadLine();
var list = new List<Mark>();
list.Add(new Mark { Subject = SubjectEnum.Subject1, Value = Convert.ToDecimal(s1), });
list.Add(new Mark { Subject = SubjectEnum.Subject2, Value = Convert.ToDecimal(s2), });
marks.Add(Convert.ToInt32(id), list)
}
else
{
Console.WriteLine("id not found");
}
Hope this helps.