I'm making an attempt at looping through Course objects and displaying them to the console. For some reason however my solution doesn't seem to work, can anyone detect any obvious issues that I might be the cause for this? thanks :)
class Course
{
private int v1;
private string v2;
private string v3;
private int v4;
public Course(int v1, string v2, string v3, int v4)
{
this.v1 = v1;
this.v2 = v2;
this.v3 = v3;
this.v4 = v4;
}
public int courseCode { get; set; }
public string courseName { get; set; }
public string professor { get; set; }
public int capacity { get; set; }
}
class Computation
{
public static List<Course> courses = new List<Course>();
public static void addCourse(Course c)
{
courses.Add(c);
}
public static void viewCourses()
{
foreach(var c in courses)
{
Console.WriteLine(c.courseName);
}
}
}
Main
static void Main(string[] args)
{
Course computerScience = new Course(1, "Computer Science", "Dr Shkhla", 200);
Course mathematics = new Course(2, "Mathematics", "Dr Shkhla", 200);
Course physics = new Course(3, "Physics", "Dr Shkhla", 200);
addCourse(computerScience);
addCourse(mathematics);
addCourse(physics);
viewCourses();
}
The problem is that you are never assigning anything to those properties. Also, it is a very good time to learn standard naming conventions:
public class Course
{
public Course(int code, string name, string professor, int capacity)
{
Code = code;
Name = name;
Professor = professor;
Capacity = capacity;
}
// properties should be in PascalCase
// and should not have their entity's name as prefix
public int Code { get; set; }
public string Name { get; set; }
public string Professor { get; set; }
public int Capacity { get; set; }
}
Names that are sequences (v1, v2, etc in your code) should be avoided most of the times.
Also, notice that I deleted the unused properties from the class.
Change your constructor to:
public Course(int courseCode, string courseName, string professor, int capacity)
{
this.courseCode = courseCode;
this.courseName = courseName;
this.professor = professor;
this.capacity = capacity;
}
You need to update your constructor:
public Course(int v1, string v2, string v3, int v4)
{
courseCode = v1;
courseName = v2;
professor = v3;
capacity = v4;
}
or set your properties directly:
Course computerScience = new Course
{
courseCode = 1,
courseName = "Computer Science",
professor = "Dr Shkhla",
capacity = 200
};
If you like to have an nicer console output, override your toString() function of the Course model.
public override string ToString()
{
return $"Course {courseCode}: {courseName} by {professor}. Capacity: {capacity}";
}
Related
I have been trying to print the information about whether the equipment is mobile or immobile, but for some reason it isn't showing any output.
public class Equipment
{
public string name;
public string description;
public string type;
public int distance_moved = 0;
public int wheels = 0;
public int weight = 0;
public int maintenance_cost;
public Equipment(string n, string d, string t, int w, int wt)
{
n = name;
d = description;
t = type;
w = wheels;
wt = weight;
}
public void Move_By(int d)
{
distance_moved = distance_moved + d;
if (this.type == "Mobile")
{
maintenance_cost = wheels * distance_moved;
}
else maintenance_cost = weight * distance_moved;
}
}
class Program
{
static void Main(string[] args)
{
var Equipment_list = new List<Equipment>()
{
new Equipment("Bulldozer", "Light Vehicle", "Mobile",4,0),
new Equipment("Box", "Huge Box", "ImMobile",0,10),
new Equipment("Drill Machine", "Light Machine", "ImMobile",0,20),
new Equipment("Truck", "Heavy Vehicle", "Mobile",4,0)
};
var Mobile_Equipment = from Mobile in Equipment_list
where Mobile.type == "Mobile"
orderby Mobile.name
select Mobile;
foreach (var Mobile in Mobile_Equipment)
{
Console.WriteLine("{0} is a Mobile Equipment", Mobile.name);
}
Console.ReadKey();
}
}
Your Equipment constructor is doing all of its assignments backwards. You're assigning the default class member values to the method arguments. It should be like this instead:
public Equipment(string n, string d, string t, int w, int wt)
{
name = n;
description = d;
type = t;
wheels = w;
weight = wt;
}
The assignments in Equipment's constructor are in the wrong order. It's not a good idea to use public fields either. Fields are implementation details, even if they are public.
The class should look like this:
public class Equipment
{
public string Name {get;set;}
public string Description {get;set;}
public string Type {get;set;}
public int Distance_moved {get;set;}= 0;
public int Wheels {get;set;} =0;
public int Weight {get;set;} =0;
public int Maintenance_cost {get;set;} =0;
public Equipment(string name, string description, string type,
int wheels, int weight)
{
Name = name;
Description = description;
Type = type;
Wheels = wheels;
Weight = weight;
}
In the following code, I'm trying to learn how to get objects to interact with each other, because I feel that's a bit more important than what I have done now which is simply collect a bunch of variables assign to each object.
For fun, what I want these different objects to do is to kill each other. The person named Jack can kill. The other two can not. What I want Jack to do is strike the other two, making them lose 1, 5 or 10 HitPoints multiple times until they are dead, and then set their Alive to false.
I don't know how to even start this, but I think it would be a very fun and interesting exercise.
The most important thing about doing this is learning how one object can directly change something about a different object, just because it can, and that the objects it has then changed, will then suffer a consequence from this action.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOP_Learning
{
class Program
{
static void Main(string[] args)
{
Person p1;
p1 = new Person("Jack", 27, true, true, 10);
Person p2;
p2 = new Person("Vincent", 63, true, false, 10);
Person p3;
p3 = new Person("Tim", 13, true, false, 10);
Console.ReadLine();
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public bool Alive { get; set; }
public bool AbilityToKill { get; set; }
public int HitPoints { get; set; }
public Person(string name, int age, bool alive, bool abilityToKill, int hitPoints)
{
HitPoints = hitPoints;
AbilityToKill = abilityToKill;
Alive = alive;
Name = name;
Age = age;
}
}
}
You need 2 methods in the Person class.
Hit -> This method reduce the HitPoints on self object with each hit. When the HitPoints become Zero, status Alive is set to false.
Kill -> This will take person as a parameter and call Hit method on that person till that person is Alive.
Add following methods to Person class:
public void Hit()
{
if(Alive)
{
if(HitPoints > 0)
{
HitPoints -= 1;
}
else
{
Alive = false;
}
}
}
public bool Kill(Person person)
{
if(!AbilityToKill)
{
Console.WriteLine("You don't have ability to kill! You cannont kill {0}.", person.Name);
return false;
}
while(person.Alive)
{
person.Hit();
}
Console.WriteLine("{0} is dead.", person.Name);
return true;
}
Call Kill method in Main method.
p2.Kill(p3);
p1.Kill(p2);
p1.Kill(p3);
Hope this helps!
Is this the kind of thing you mean?
public class Person
{
public string Name { get; private set; }
public int Age { get; private set; }
public bool Alive { get; private set; }
public bool AbilityToKill { get; private set; }
public int HitPoints { get; private set; }
public void Hit(int points)
{
this.HitPoints -= points;
if (this.HitPoints <= 0)
{
this.HitPoints = 0;
this.Alive = false;
}
}
public Person(string name, int age, bool alive, bool abilityToKill, int hitPoints)
{
this.HitPoints = hitPoints;
this.AbilityToKill = abilityToKill;
this.Alive = alive;
this.Name = name;
this.Age = age;
}
}
Now with the check for AbilityToKill:
public class Person
{
public string Name { get; private set; }
public int Age { get; private set; }
public bool Alive { get; private set; }
public bool AbilityToKill { get; private set; }
public int HitPoints { get; private set; }
public int Attack(Person victim, int points)
{
var hp = victim.HitPoints;
if (this.AbilityToKill)
{
victim.HitPoints -= points;
if (victim.HitPoints <= 0)
{
victim.HitPoints = 0;
victim.Alive = false;
}
}
hp -= victim.HitPoints;
return hp;
}
public Person(string name, int age, bool alive, bool abilityToKill, int hitPoints)
{
this.HitPoints = hitPoints;
this.AbilityToKill = abilityToKill;
this.Alive = alive;
this.Name = name;
this.Age = age;
}
}
This can be used like this:
var jack = new Person("Jack", 27, true, true, 10);
var vincent = new Person("Vincent", 63, true, false, 10);
var tim = new Person("Tim", 13, true, false, 10);
var damage_done = jack.Attack(vincent, 20);
Console.WriteLine(damage_done);
The Attack method returns the actual number of hits points reduced by the attack - the damage dealt.
And here's a more strongly-typed version. Using bool for properties isn't always the clearest way to code. Through in some enums and it's clearer.
public class Person
{
public string Name { get; private set; }
public int Age { get; private set; }
public Alive Alive { get; private set; }
public AbilityToKill AbilityToKill { get; private set; }
public int HitPoints { get; private set; }
public int Attack(Person victim, int points)
{
var hp = victim.HitPoints;
if (this.AbilityToKill == AbilityToKill.Yes)
{
victim.HitPoints -= points;
if (victim.HitPoints <= 0)
{
victim.HitPoints = 0;
victim.Alive = Alive.No;
}
}
hp -= victim.HitPoints;
return hp;
}
public Person(string name, int age, Alive alive, AbilityToKill abilityToKill, int hitPoints)
{
this.HitPoints = hitPoints;
this.AbilityToKill = abilityToKill;
this.Alive = alive;
this.Name = name;
this.Age = age;
}
}
public enum Alive { Yes, No }
public enum AbilityToKill { Yes, No }
It's used like this:
var jack = new Person("Jack", 27, Alive.Yes, AbilityToKill.Yes, 10);
var vincent = new Person("Vincent", 63, Alive.Yes, AbilityToKill.No, 10);
var tim = new Person("Tim", 13, Alive.Yes, AbilityToKill.No, 10);
var damage_done = jack.Attack(vincent, 20);
Console.WriteLine(damage_done);
First, i'm a beginning in c#. I'm try to code some game. I don't know how to return enum value as string.
Here my code.
public class CARDS {
public CARDS(int id, int atk, ClassType ctype, string name) {
this.CARD_ID = id;
this.C_TYPE = ctype;
this.ATK = atk;
this.NAME_EN = name;
}
public CARDS() {
this.CARD_ID = -1;
}
public int CARD_ID { get; set; }
public ClassType C_TYPE { get; set; }
public int ATK { get; set; }
public string NAME_EN { get; set; }
public enum ClassType {
Warrior,
Mage,
Archer,
Thief,
Bishop,
Monk,
Guardian,
Destroyer,
Chaser,
Hermit,
Alchemy
}
}
.......
Here I try to do.
public class CardCollection : MonoBehaviour {
private List<CARDS> dbase = new List<CARDS>();
private JsonData cardsdata;
private JsonData card;
void Start() {
cardsdata = JsonMapper.ToObject(File.ReadAllText(Application.dataPath + "/Json/card.json"));
ConstructCardData();
Debug.Log(dbase[1].NAME_EN + " " + dbase[23].NAME_EN);
}
void ConstructCardData() {
card = cardsdata["CARDS"];
for (int i = 0; i < card.Count; i++) {
dbase.Add(new CARDS((int)card[i]["CARD_ID"], (int)card[i]["ATK"], card[i]["C_TYPE"].ToString(), card[i]["NAME_EN"].ToString()));
}
}
}
// card[i]["C_TYPE"].ToString()
It say can't convert from string to CARDS.ClassType
What about :
public class CARDS
{
public CARDS(int id, int atk, ClassType ctype, string name)
{
this.CARD_ID = id;
this.C_TYPE = Enum.GetName(ctype.GetType(), ctype); //Use Enum.GetName to get string
this.ATK = atk;
this.NAME_EN = name;
}
public CARDS()
{
this.CARD_ID = -1;
}
public int CARD_ID { get; set; }
public string C_TYPE { get; set; } //change type to string
public int ATK { get; set; }
public string NAME_EN { get; set; }
public enum ClassType
{
Warrior,
Mage,
Archer,
Thief,
Bishop,
Monk,
Guardian,
Destroyer,
Chaser,
Hermit,
Alchemy
}
}
ToString() on the enum values return the string value of the enum. Custom string values can also be returned for the enum values, check these links, link1 , link2
Examples:
ClassType.Warrior.ToString();
ctype.ToString();
is there a way to put these into either a 1 D array or a 2 D array. ? i have produced code and it looks a bit untidy as well as long can this be shortened?
double worstPrice = 6.47;
double bestPrice = 0.99;
double CivetCatPrice =29.14;
double whenPrice = 10.50;
double everythingPrice = 319.56;
int bestStock = 3238;
int worstStock = 8;
int civetCatstock = 3;
int whenStock = 37;
int everythingStock = 2;
You can make an array for each doubles and ints like this
double[] priceData = new double[]{ 6.47, 0.99, 29.14, 10.50, 319.56 };
int[] stockData = new int[]{ 3238, 8, 3, 37, 2 };
Alternatively you can use a dictionary if you wish for them to keep their names
Dictionary<string, double> priceDict = new Dictionary<string, double>();
priceDict.Add("worstPrice", 6.47);
//And so on for each double
Dictionary<string, int> stockDict = new Dictionary<string, int>();
priceDict.Add("bestStock", 3238);
//And so on for each int
The values in these can be called like so
double worstMinusBestPrices = priceData[0] - priceData[1]; //For arrays
double worstMinusBestPrices = priceDict["worstPrice"] - priceDict["bestPrice"] //For dictionaries
You could implement a custom class which holds these values as proprties with meaningful names. Then your code will be much more readable, maintainable and robust.
For example (you don't need all of these classes, it should just give you an idea):
public abstract class Animal
{
public Animal(string animalName)
{
this.Name = animalName;
}
//insert properties and methods which all aimals share here
public string Name { get; set; }
}
public class CibetCat : Animal
{
public CibetCat() : base("CibetCat")
{
}
//insert properties and methods which all CibetCats share here
}
Now your class that holds the price and stock informations as well as the reference to the animal itself(CibetCat in your example):
public class AnimalStock // or AnimalPrice or whatever
{
public AnimalStock(Animal animal)
{
this.Animal = animal;
}
public AnimalStock(Animal animal, decimal worstPrice, decimal bestPrice, int bestStock, int worstStock)
{
this.Animal = animal;
this.Worstprice = worstPrice;
this.BestPrice = bestPrice;
this.BestStock = bestStock;
this.WorstStock = worstStock;
}
public Animal Animal { get; set; }
public decimal Worstprice { get; set; }
public decimal BestPrice { get; set; }
public int BestStock { get; set; }
public int WorstStock { get; set; }
// ...
}
Lot of code but not complex. Now You can write this simple and readable code:
Animal cibetCat = new CibetCat();
AnimalStock stock = new AnimalStock(cibetCat);
stock.BestPrice = 0.99m;
stock.Worstprice = 6.47m;
stock.BestStock = 3238;
// ...
Later you can access all these properties(or it's methods) from a single instance.
Console.WriteLine("Animal's best-price is: {0}", stock.BestPrice); // etc
As Alfie pointed out, you could use a dictionary - but you're then referencing things by a string identifier, that you have to remember.
Another way would be to use a class or struct. There are of course many ways to do this, but some include:
public class Things
{
public double worstPrice = 6.47;
public double bestPrice = 0.99;
public double CivetCatPrice =29.14;
public double whenPrice = 10.50;
public double everythingPrice = 319.56;
public int bestStock = 3238;
public int worstStock = 8;
public int civetCatstock = 3;
public int whenStock = 37;
public int everythingStock = 2;
}
Another way would be:
public class Things
{
public double WorstPrice { get; readonly set; }
public double BestPrice = { get; readonly set; }
// etc
public Things(double worstPrice, double bestPrice) // etc
{
WorstPrice = worstPrice;
BestPrice = bestPrice;
}
}
There are pros and cons to both approaches. Another potential is to use a collection of a class/struct to group things and aggregate them in meaningful ways.
Like:
public class Thing
{
public string ThingLabel { get; readonly set; }
public double ThingPrice { get; readonly set; }
public int ThingQuantity { get; readonly set; }
// the value of your stock, calculated automatically based on other properties
public double ThingValue { get { ThingPrice * ThingQuantity; } }
public Thing(string thingLabel, double thingPrice, int thingQuantity)
{
ThingLabel = thingLabel;
// etc
}
}
public void DoStuff()
{
List<Thing> list = new List<Thing>();
Thing thing = new Thing("Civet cat", 500, 10);
list.Add(thing);
list.Add(new Thing("Sea flap flap", 100, 5);
list.Add(new Thing("Nope Rope", 25, 4);
Console.WriteLine("The value of {0}'s stock is: {1}", thing.ThingLabel, thing.Value);
}
and yet another way is to use a base class and create sub classes of your different types. The possibilities are nearly endless! You just have to decide which way works best for you now, you later, and your potential team.
Hi I have had to use interfaces before but ive been told i need to implement icomparable in this instance. see below:
internal class doorItem : IComparable
{
public int CompareTo(doorItem other)
{
// The temperature comparison depends on the comparison of the
// the underlying Double values. Because the CompareTo method is
// strongly typed, it is not necessary to test for the correct
// object type.
return GetNumber(productSize).CompareTo(GetNumber(other.productSize));
}
public string variations { get; set; }
public double pricerange { get; set; }
public string viewDetailsLink { get; set; }
public string height { get; set; }
public string width { get; set; }
public string productSize { get; set; }
public string productImage { get; set; }
public int countItemsOnSale { get; set; }
public string optionFor35Product { get; set; }
private int GetNumber(string str)
{
//this method gets the int out of the string
int length = str.Length;
string output = String.Empty;
int test = 0;
bool err = false;
for (int i = 0; i <= length; i++)
{
try
{
test = Convert.ToInt32(str.Substring(i, 1));
}
catch
{
err = true;
}
if (!err)
output += str.Substring(i, 1);
else
break;
}
return Convert.ToInt32(output);
}
}
above is the class i have created, door sizes are returned like this: 4dr, 5dr, 6dr etc.. then the getnumber method gets the int out of the string.
i have a generic list in of my custom class in the main method like this:
List<doorItem> d = new List<doorItem>();
i cant work out how to order this list by door size.... PLEASE HELP
It's easiest to do this using LINQ. Then you don't even need to implement IComparable.
var sortedList = doorList.OrderBy( d => d.GetNumber(d.productSize ).ToList();
And make GetNumber public inside the doorItem class.
I don't know if performance is important, but that method for getting the number is pretty horrible, exceptions should only be used in exceptional circumstances! Suggest something like this
StringBuilder sb = new StringBuilder();
foreach (char c in str)
{
if (Char.IsNumber(c))
{
sb.append(c);
}
}
return Convert.ToInt32(sb.ToString());
For sorting you can do what stecya has suggested, or you could convert this method to a property and sort directly.
public int Size
{
get
{
return GetNumber(this.productSize);
}
}
...
d.OrderBy(x=>x.Size);