This Is my Assignment, I am having Troubles Getting my Class To Work With main for, Can Someone please Help Me, This is due on Tuesday and I have been hitting a brick wall in every approach I have tried. all my class and my forms are posted. Please Help me I am totally lost and frustrated
1.Employee and ProductionWorker Classes
Create an Employee class that has properties for the following data:
•Employee name
•Employee number
Next, create a class named ProductionWorker that is derived from the Employee class.
The ProductionWorker class should have properties to hold the following data:
•Shift number ( an integer, such as 1, 2, or 3)
•Hourly pay rate The workday is divided into two shifts: day and night.
The Shift property will hold an integer value representing the shift that the employee works. The day shift is shift 1 and the night shift is shift 2.
Create an application that creates an object of the ProductionWorker class and lets the user enter data for each of the object’s properties. Retrieve the object’s properties and display their values.
This Is My Employee Reference Chart. To Store Their Names And I.D Numbers I am getting no compiling errors on this class, however I am not sure if I am doing this correctly because in my main I get a compiling error.
I assume I need an array to store all the data that will be inputted into my TextBox in visual
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Employee_References
{
class Roster
{
// Field for name, ID, dept, and position
private const int NAMES = 100;
private static string [] employee = new string [NAMES];
private const int NUMBER = 100;
private static int [] id = new int [NUMBER];
private int total = 0;
public void Employee()
{
total = 0;
}
// This will recieve input from my main
public static void employeeName (string [] xArray)
{
for (int index = 0; index < xArray.Length; index++)
{
xArray[index] = employee[NAMES];
}
}
// This will recieve input from my main
public static void idNumber ( int [] zArray)
{
for (int index = 0; index < zArray.Length; index++)
{
zArray[index] = id[NUMBER];
}
}
}
}
This will be my next class that is derived from my first class as my assignment requested. This class is suppose to store the shift numbers 1 through for 4, and an hourly wage setter for a Day and Night Shift. I am getting one compiling error in this class that says " The left-hand side of an assignment must be a variable, property or indexer" I am not sure What it is telling me, can someone please explain what it is trying to tell me. Am I doing this correctly?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Employee_References
{
class References : Roster
{
// Field for name, ID, dept, and position
private int shift;
private static const double PAYRATEDAY = 12.75;
private static const double PAYRATENIGHT = 15.75;
public void Employee()
{
}
// This will recieve input from my main
public int shifts
{
set {shift = value;} // this set the recieve value of name one and set it to name1
get {return shift; } //this will get name1 and send it to my main.
}
// This will recieve input from my main
public double payrate1
{
set { PAYRATEDAY = value; } // ERROR!!The left-hand side of an assignment must be a variable, property or indexer
get { return PAYRATEDAY; }
}
// This will recieve input from my main
public double payrate2
{
get { return PAYRATENIGHT; } // ERROR!!The left-hand side of an assignment must be a variable, property or indexer
set { PAYRATENIGHT = value; }
}
}
This is my Form, I am trying to send my input values into my class my "Roster" class That has an array of 100. How ever I keep getting a compiling error that says " Cannot assign to 'employeeName' because it is a 'method group". I am not sure What It is telling me can some one explain this to me, and give me some pointer on how to do this
using System;
using System.Windows.Forms;
namespace Employee_References
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Roster Chart = new Roster();
Chart.employeeName = name.Text; // Error **Cannot assign to 'employeeName' because it is a 'method group**".
}
}
}
employeeName() is a method and you are trying to assign it a value.
Looks like you want to try and pass an array of names to it as a parameter
//first define and populate myArray
Chart.employeeName(myArray)
You say
private static const double PAYRATEDAY = 12.75;
Then
public double payrate1
{
set { PAYRATEDAY = value; } // ERROR!!The left-hand side of an assignment must be a variable, property or indexer
get { return PAYRATEDAY; }
}
Why do you declare the field constant if you are changing it?
Also, I think you'd be better off using lists instead of arrays, so that it can grow dynamically as much as it needs instead of being limited by a fix number.
Related
I've been working on this for so long but unfortunately, I'm not progressing at all. I am creating a personality quiz in Unity wherein each question have choices where in depending on each choice, a certain variable is increasing in value. The quiz seeks to show the user's top 5 best fit patterns (which is the variable with the highest value) based on his personality which will be based upon his answers. The public voids are called depending on which choice/button was clicked through the on click in the inspector.
public class QuizScript : MonoBehaviour {
public int snake = 0;
public int centipede = 0;
public void Q2C1() //question 2 choice 1
{
snake = snake + 1;
Debug.Log("Snake = " + snake); //for me to see if it works
}
public void Q3C1() //question 3 choice 1
{
centipede = centipede + 1;
Debug.Log("Centipede = " + centipede);
}
}
There are 26 patterns in all but in the mean time, I just want to sort two variables which are the snake and the centipede. I have searched for tutorials about sorting variables and there are short and long methods. But either way, I am having a hard time understanding it and applying it in my code. In one method, it is required to use another public static void or static int to do the sorting, but what confuses me is how will I be able to call it inside another public void which will be the one called and done when the button is clicked, which is not possible after trying it in the code. (Also, public static void does not recognize the already declared variables inside the class which is a big problem.) I have thought of calling the static void separately in the on click of the button that can be seen in the inspector but maybe because it is a static void, I cannot find it in the options.
This is the code where I am unable to call static int SortByScore in the inspector.
static int SortByScore(int snake, int centipede)
{
return centipede.CompareTo(snake);
}
Thank you so so much in advance for the help. :)
I would look into using some sort of Dictionary type in order to achieve this.
You want to have a list of values that are tied together so you need an appropriate data type in order to do that. In the solution I propose, we use an enum to make a strong type out of the outcomes in your quiz, tying them together by using a Dictionary (which is a key-value table) and you can then order these using LINQ to get the outcome.
public class QuizScript : MonoBehavior {
public Dictionary<Outcome, int> Outcomes = new Dictionary<Outcome, int>() {
{ Outcome.Snake, 0 },
{ Outcome.Centipede, 0 }
};
public void Q2C1() {
Outcomes[Outcome.Snake]++;
Debug.Log("Snake: " + Outcomes[Outcome.Snake]);
}
public void Q3C1() {
Outcomes[Outcome.Centipede]++;
Debug.Log("Centipede: " + Outcomes[Outcome.Centipede]);
}
public Outcome GetHighestOutcome() {
// Order by the 'key' of the dictionary, i.e. the number we tied to the outcome
return Outcomes.OrderByDescending(choice => choice.Value).FirstOrDefault().Key;
}
}
public enum Outcome {
Snake,
Centipede
}
At OP's additional request, you could do a sort and then get the top items like so:
public List<Outcome> GetHighestOutcome() {
// Order by the 'key' of the dictionary, i.e. the number we tied to the outcome
var maxValue = Outcomes.OrderByDescending(choice => choice.Value).FirstOrDefault().Value;
var kvPairs = Outcomes.Find(kv => kv.Value == maxValue);
return kvPairs.Select(kv => kv.Key).ToList();
}
I think your strategy is getting in-your-way. This is a good example where you would be better-off storing your values in a HashSet or Dictionary.
This is how your code would look if you used a Dictionary instead:
public class QuizScript : MonoBehaviour {
public System.Collections.Generic.Dictionary<string, int> characteristic = new Dictionary<string, int>();
//public int snake = 0;
//public int centipede = 0;
//constructor initializes your set
public QuizScript() {
characteristic.Add("snake",0);
characteristic.Add("centipede",0);
}
public void Q2C1() //question 2 choice 1
{
characteristic["snake"] += 1;
Debug.Log("Snake = " + characteristic["snake"].ToString()); //for me to see if it works
}
public void Q3C1() //question 3 choice 1
{
characteristic["centipede"] += 1;
Debug.Log("Centipede = " + characteristic["centipede"].ToString());
}
}
What's your goal at the end of the project? Do you want to display the variables in order from biggest to smallest? If so, you could load all the variables into an array, and let the array do the sorting for you. The Array class has a Sort() function!
So, for example, you could have an int array of variables underneath your other variable declarations, then you could load the array with all your variables:
variableArray = {snake, centipede, ...} //the rest of your variables
Then, use the Array class' Sort function to sort it for you. Check out how to declare an array and how to use Array's Sort function, and you should be all set.
Good luck!
I am a bit confused with the get set property in C#.
I have the simple code below:
using System;
class Example
{
int _number;
public int Number
{
get
{
return this._number;
}
set
{
this._number = value;
}
}
}
class Program
{
static void Main()
{
Example example = new Example();
example.Number = 5; // set { }
Console.WriteLine(example.Number); // get { }
}
}
The code above using get set properties. However, if I delete the get set code like below code, the results stay the same.
using System;
class Example
{
int _number;
public int Number;
{
}
}
class Program
{
static void Main()
{
Example example = new Example();
example.Number = 5; // set { }
Console.WriteLine(example.Number); // get { }
}
}
My query is, what is the get set code used for? In the above program, the results are same. Can you give me some simple code which show the get set usage?
In your code, Number is simply a public field, as evidenced by the semicolon (;) at the end.
public int Number;
It is not a property, you just have an empty set of brackets right underneath which led to your confusion. If you were to remove the ; then you would actually have a property that is missing it's get, and would not compile at all.
All properties need to have a getter (setters are optional). If you want to avoid writing them, you can use auto properties, which take care of the backing field without you having to get involved:
public int Number { get; set; } // No field required
Note: A common usage pattern you'll see involving auto properties is the following:
public int Number { get; private set; }
This allows for properties that can be read from anywhere, but can only be modified from within the class they belong to.
EDIT: To answer your question, the main difference between fields and properties is in encapsulation. You can read more about the general differences between fields and properties here.
However, the example you have given has one additional difference, the private set. A normal field can be written from and to throughout the program. A property with a private setter however can only be modified from inside the class it belongs to.
Example:
public class Foo
{
public int Id { get; private set; }
public string Name;
public Foo()
{
this.Id = 1; // This works!
}
}
Here, Name is a field and Id is a property with a private setter. Notice that we modify Id in the constructor and that works, because it is within the class Id belongs to. Moving outside the class however:
var foo = new Foo();
// Field (no get and set):
foo.Name = "test" // Works
string bar = foo.Name; // Works
// Property (get and *private* set)
int i = foo.Id; // Works, because get is public
foo.Id = 2; // Doesn't work, because set is private
The question: How can i link the user input to a specific constructor and create an object when the user clicks on Add.
How i created my project:
I created a console application. A class named car with the following attributes:
Brand name
Type
Mileage
Commissioning date
Numberplate
Horsepower
Number of gears
Number of seats
Volume of the trunk
Fuel consumption
2 Constructors: 1 with everything except number of seats. Second with everything except number of gears.
A method that adds to the fuel consumption depending on how many numbers of gears or number of seats.
Everything works well. I now created a windows form. Changed output type to windows form instead of console.
For the windows form:
The user has to choose between 2 options: A sports car or a family car. Depending on which option the user chooses, for the sports car all attributes except for number of seats. For the family car, everything except for number of gears. The user has to fill in the name of the car, type, etc.
Then the user needs to click on the button named Add in order to see the consumption of the vehicle. Later in the project, i need to create it so that the user is able to delete it by typing in the numberplate.
namespace Sportwagens {
public class Wagen
{
string Merk;
string Type;
int Aantalkm;
DateTime Ingebruiknamedatum;
string Nummerplaat;
int Pk;
int Brandstofverbruik;
public class Sportwagen : Wagen
{
int Aantalvitessen;
public Sportwagen(string merk, string type, int aantalkm, DateTime ingebruiknamedatum, string nummerplaat, int pk, int aantalvitessen, int brandstofverbruik)
{
Merk = merk;
Type = type;
Aantalkm = aantalkm;
Ingebruiknamedatum = ingebruiknamedatum;
Nummerplaat = nummerplaat;
Pk = pk;
Aantalvitessen = aantalvitessen;
Brandstofverbruik = brandstofverbruik;
}
public int vermeerderingbrandsotfverbruiksportwagen()
{
if (Aantalvitessen >= 6)
{
Brandstofverbruik += 2;
}
return Brandstofverbruik;
}
}
class Gezinswagen : Wagen
{
int Aantalzitplaatsen;
int Koffervolume;
public Gezinswagen(string merk, string type, int aantalkm, DateTime ingebruiknamedatum, string nummerplaat, int pk, int aantalzitplaatsen, int koffervolume, int brandstofverbruik)
{
Merk = merk;
Type = type;
Aantalkm = aantalkm;
Ingebruiknamedatum = ingebruiknamedatum;
Nummerplaat = nummerplaat;
Pk = pk;
Aantalzitplaatsen = aantalzitplaatsen;
Koffervolume = koffervolume;
Brandstofverbruik = brandstofverbruik;
}
public int vermeerderingbrandsotfverbruikgezinswagen()
{
if (Aantalzitplaatsen >= 7)
{
Brandstofverbruik += 1;
}
return Brandstofverbruik;
}
}
public Wagen()
{
}
public Wagen(string merk, string type, int aantalkm, DateTime ingebruiknamedatum, string nummerplaat)
{
Merk = merk;
Type = type;
Aantalkm = aantalkm;
Ingebruiknamedatum = ingebruiknamedatum;
Nummerplaat = nummerplaat;
}
Click here to see how the form looks like
If the 'car' object is instantiated when the user chooses between the two options, you could simply change the order of the arguments in each constructor (assuming that there are arguments of different types).
For example, if one constructor was:
public Car(string brandName, string type, double mileage ...)
{
...
}
And the other was:
public Car(string brandName, double mileage, string type ...)
{
...
}
You could force the class to use one or the other based on the order in which you give the parameters. However this is not good practice.
From your description, it sounds as though you should create two 'subclasses', (SportsCar and FamilyCar) and use inheritance to achieve your goal, or composition.
Double click on the "Toevoegen" button in the form editor. That should create a method that looks a bit like this:
private void button1_Click(object sender, EventArgs e)
{
}
Outside the method, declare an instance of the 'Wagen' class like so:
Wagen mijnWagen;
Then, inside the button_click method, initialise the instance of the wagen object as follows:
if (//"Sportswagen is selected")
{
mijnWagen = new Sportwagen(merk, type etc. as filled in on form);
}
else
{
mijnWagen = new Gezinswagen(merk, type etc. as filled in on form);
}
Now, when the button is clicked, the object mijnWagen will be initialised to whichever type of car they selected.
I'm making an item system for my Unity game, and I'm using C# to do it. I have an abstract class called ItemType, which contains information about a particular type of items(such as its name, its weight, its market value, its id, etc.). I then have to item classes, ItemSword, and ItemCoin, which inherit from the ItemType class. I also have an ItemManager class, which instantiates ItemCoin and ItemSword and automatically assigns them an ID for me. My problem is that I'm getting an error with the constructors when I try to inherit the classes.
The constructor for ItemType takes one parameter, a string called name. When I go to do the constructor for ItemCoin, I make sure it calls the base class using
ItemCoin(string name): base(name){
//Stuff
}
just like it says on this page.
The error is saying that "name" is inaccessible due to its protection level, as if I had made it private. I don't get how this is possible, though, since I'm not giving it any kind of access modifiers because it's a parameter. ItemSword is not giving me this error, but that's likely because the compiler is still stuck on ItemCoin.
When I don't give "base" any parameters, it tells me that ItemType does not have a constructor with 0 parameters. The same thing happens if I don't use "base" at all, or if I don't give it any constructor.
For reference, here is my full source code.
ItemType.cs:
using UnityEngine;
using System.Collections;
public abstract class ItemType{
public int itemID; //The id of this item
public string itemName; //The text name of this item
public int stackSize = 99; //The maximum amount of this item allowed in a stack. Use -1 for infinite
public int maxAllowedInOneContainer = -1; //The maximum amount of this item allowed in a single container. Use -1 for infinite.
public int weight = 0; //The weight of this item
public int marketValue = 0; //The standard price of this item in stores
ItemType(string name){
itemName = name;
}
}
ItemCoin.cs:
using UnityEngine;
using System.Collections;
public class ItemCoin : ItemType {
ItemCoin(string name): base(name){
stackSize = -1;
}
}
ItemSword.cs:
using UnityEngine;
using System.Collections;
public class ItemSword : ItemType{
ItemSword(string name): base(name){
maxAllowedInOneContainer = 1;
stackSize = 1;
}
}
ItemManager.cs:
using UnityEngine;
using System.Collections;
public class ItemManager {
public const int MAX_ITEMS = 3200;
private static ItemType[] itemList = new ItemType[MAX_ITEMS];
public static int numberOfItems = 0;
ItemManager(){
/*When you make a new item, add it to this huge list of item declarations, or else it won't do anything!*/
ItemSword sword = addItem(new ItemSword("Sword")); //Adds the sword item
ItemCoin coin = addItem(new ItemCoin("Coin"));
}
public ItemType addItem(ItemType item){
//Add the item to the list
itemList[numberOfItems] = item;
//Tell the item its id number
item.itemID = numberOfItems;
//Increment the total number of items by one. This will be the id of the next added item.
numberOfItems += 1;
return item;
}
public int findItemID(string name){
//Finds the item id for an item with a given name
bool found = false;
for (int i = 0; i < numberOfItems; i++){
if (itemList[i].itemName == name){
found = true;
return itemList[i].itemID;
break;
}
}
if (found == false){
throw new ItemIDNotFoundException();
}
}
public string findItemName(int id){
if (id >= itemList.Length){
throw new ItemIDNotFoundException();
}
else{
return itemList[id].name;
}
}
public ItemType GetItem(int id){
//Returns a reference(pointer) to the item type with a given id.
return itemList[id];
}
}
Within classes, private is the default accessibility level, so by not specifying it, your constructor is private.
When you have a constructor like this:
ItemType(string name){
itemName = name;
}
it is private and can only be accessed by the class itself. private is the default for class members when no access modifier is specified. In order to be able to use it from a subclass, you need to make it at least protected:
protected ItemType(string name)
{
itemName = name;
}
Or you can make it public or internal. Since this is an abstract class and it wouldn't make sense to access it from anything other the class itself or a subclass, protected is probably the most appropriate option.
In classes, the default accessibility level is private. If you not specify it, then your constructors will be private.
From MSDN;
Note that if you do not use an access modifier with the constructor it
will still be private by default. However, the private modifier is usually used explicitly
to make it clear that the class cannot be instantiated.
I've got a program snippet here that allows the creation of an Employee object with simple properties of age, id, name and pay. Just playing around with it I noticed that
Console.WriteLine(joe.Age+1); is my Main() method returns one,
but Console.WriteLine(joe.Age++); returns 0. I know that the Age property, per the constructors is going to be initialized to 0, but why isn't 1 being added with the ++ operator? EDIT: I found the source of the strange behavior. In the Age property I have empAge=Age when it should've been equal to value
source:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EmployeeApp
{
class Employee
{
//field data
//notice the the fields are declared as private
//these fields are used in the constructors
private string empName;
private int empID;
private float currPay;
private int empAge;
//properties! private field data should be accessed via public properties
//note that properties don't use parentheses ()
//within the set scope you see the 'value' contextual keyword
//it represents the value being assigned by the caller and it will always be the same
//underlying data type as the property itself
public int Age
{
get { return empAge; }
set { empAge = Age; }
}
public string Name
{
get { return empName; }
set
{
if (value.Length > 15)
Console.WriteLine("this name is too long.");
else
empName = value;
}
}
public int ID
{
get { return empID; }
set { empID = value; }
}
public float pay
{
get { return currPay; }
set { currPay = value; }
}
//constructors
public Employee() { }
public Employee(string name, int id, float pay, int age)
{
empName = name;
empID = id;
currPay = pay;
empAge = age;
}
//methods
//the int parameter that this method takes will come from somewhere in the Main method
//currpay is a private field
public void GiveBonus(float amount)
{
currPay += amount;
}
public void DisplayStats()
{
Console.WriteLine("name: {0}", empName);
Console.WriteLine("ID: {0}", empID);
Console.WriteLine("pay: {0}", currPay);
Console.WriteLine("age: {0}", empAge);
}
}
}
Main method here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Encapsulation using traditional accessors/mutators or get/set methods
//the role of a get method is to return to the caller the current value of the underlying state data
//a set method allows the caller ot change the current value of the state data
//you need to have a getter and a setter for every field that the class has
namespace EmployeeApp
{
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("fun with encapsulation");
//Employee emp = new Employee("marvin", 456, 4000, 56);
//emp.GiveBonus(3);
// emp.DisplayStats();
// emp.Name = "wilson";
// emp.DisplayStats();
Employee joe = new Employee();
Console.WriteLine(joe.Age++);
}
}
}
The ++ incremental operator has two uses:
joe.Age++
and
++joe.Age
The first one, as you're using, is executed after the current operation. So, when you call Console.WriteLine(joe.Age++);, this can also be represented with:
Console.WriteLine(joe.Age);
joe.Age = joe.Age + 1;
So, you're passing the current value to WriteLine, and then incrementing it.
Leading with ++ will do the opposite - increment and then use the value. So, Console.WriteLine(++joe.Age); can also be read as:
joe.Age = joe.Age + 1;
Console.WriteLine(joe.Age);
When you use the unary ++ operator after the variable, the addition doesn't happen until after the outer expression is evaluated. When you use it before the variable, the addition happens before the outer expression is evaluated.
For instance,
// this will increment joe.Age, and then write it to console.
Console.WriteLine(++joe.Age);
versus
// this will write joe.Age to the console, and then increment it.
Console.WriteLine(joe.Age++);
From the docs on msdn:
The first form is a prefix increment operation. The result of the
operation is the value of the operand after it has been incremented.
The second form is a postfix increment operation. The result of the
operation is the value of the operand before it has been incremented.
In your Age property, you are not changing the empAge member to the value passed in. This is probably why you aren't seeing any changes when you tried ++ multiple times.
public int Age
{
get { return empAge; }
set { empAge = Age; } // this does not set the value!
}
Use the value instead:
public int Age
{
get { return empAge; }
set { empAge = value; } // use the value passed in
}
And as others have pointed out, you are using the postfix version of the ++ operator. The prefix version will increment the amount first before writing the property to the console.
In C++ and C#, there are two ++ operators. The first is a prefix operator (++age) and this one works as you are expecting -- increments the value and then returns the result. the postfix operator (age++) increments the value but returns the previous value.