first class as follows:
public class employeeApp
{
public static void main()
{
EmployeeProgram.employee Employee = new EmployeeProgram.employee( );
}
public void employee(int employeeNumber, string name, string dateOfHire, int monthlySalary)
{
employeeNumber = 123;
name = Cody;
dateOfHire = 01/01/11;
monthlySalary = 2500;
}
}
second class as follows:
/*
* Mosbrucker_C_PRO_01 Author: Mosbrucker, Cody
* Creates a class for employee with data members;
* Employee number, name, date of hire, and monthly salary.
* ****************************************************/
public class employee
{
private int employeeNumber;
private string name;
private string dateOfHire;
private int monthlySalary;
public int EmployeeNumber
{
get
{
return employeeNumber;
}
set
{
employeeNumber = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string DateOfHire
{
get
{
return dateOfHire;
}
set
{
dateOfHire = value;
}
}
public int MonthlySalary
{
get
{
return monthlySalary;
}
set
{
monthlySalary = value;
}
}
public override string ToString()
{
return "Employee Id: " + employeeNumber +
"Employee Name: " + name +
"Employee Date of Hire: " + dateOfHire +
"Employee Monthly Salary: " + monthlySalary;
}
}
the problems I am getting are:
*In my employeeApp class "does not contain a "static" main method for suitable entry point"
*in my employeeApp class "the name Cody does not exist in current context
*in my employeeApp class relating to dateOfHire "cannot implicitly convert int to string
I'm doing this for a class and the assignment it:
Create a Employee class. Items to include as data members are employee number, name, date of hire, and monthly salary. Include appropriate constructors and properties. Override the ToString ( ) method to return all data members. Create a second class to test your Employee class.
Any help at all is greatly appreciated.
1.in C# we use Main(Capital M) so Main method should be :
static void Main()
2.You have to create the Constructor in your class employe
3.You have to assign String to the String variable but you are assigning date.
as below :
dateOfHire = 01/01/11;
in your constructor
4.Cody should be represented as String "Cody" in your Constructor
5.while assigning data to local variables in class use this to represent current object when assigning variable have same name
example : this.employeenumber=employeenumber;
file 1:
namespace employee
{
public class employeeApp
{
public static void Main()
{
EmployeeProgram.employee Employee = new EmployeeProgram.employee(123,"Cody","11/11/11",24567);//call your constructor
}
}
}
file 2:
/*
* Mosbrucker_C_PRO_01 Author: Mosbrucker, Cody
* Creates a class for employee with data members;
* Employee number, name, date of hire, and monthly salary.
* ****************************************************/
namespace EmployeeProgram
{
public class employee
{
private int employeeNumber;
private string name;
private string dateOfHire;
private int monthlySalary;
public employee(int employeeNumber, string name, string dateOfHire, int monthlySalary)
{
this.employeeNumber = 123;
this.name = "Cody";
this.dateOfHire = "01/01/11";
this.monthlySalary = 2500;
}
public int EmployeeNumber
{
get
{
return employeeNumber;
}
set
{
employeeNumber = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string DateOfHire
{
get
{
return dateOfHire;
}
set
{
dateOfHire = value;
}
}
public int MonthlySalary
{
get
{
return monthlySalary;
}
set
{
monthlySalary = value;
}
}
public override string ToString()
{
return "Employee Id: " + employeeNumber +
"Employee Name: " + name +
"Employee Date of Hire: " + dateOfHire +
"Employee Monthly Salary: " + monthlySalary;
}
}
}
Issue 1 - C# is case sensitive. Capitalize Main. The use of the public access modifier is not necessary and is generally not recommended for Main.
static void Main()
Issue 2 - For the second name = Cody; I guess you meant...name = "Cody";
Issue 3 - For the third issue you need to convert the int values to string by calling ToString() on int values. employeeNumber.ToString() and monthlySalary.ToString().
There are lots of issues here and they are all fairly basic. I recommend you use Google or explain why exactly you could not solve them. Otherwise it might appear you have not put forth the required effort to solve the problems yourself.
Issue 4 As for the I/O write problem you need to qualify using this keyword because of the naming conflict between your local variables and private fields:
public class employee
{
private int employeeNumber;
private string name;
private string dateOfHire;
private int monthlySalary;
public employee(int employeeNumber, string name, string dateOfHire, int monthlySalary)
{
this.employeeNumber = 123;//because you have naming collissions you need to use `this`
this.name = "Cody";
this.dateOfHire = "01 / 01 / 11";
this.monthlySalary = 2500;
}
public override string ToString()
{
return "Employee Id: " + employeeNumber +
"Employee Name: " + name +
"Employee Date of Hire: " + dateOfHire +
"Employee Monthly Salary: " + monthlySalary;
}
public void Print()
{
Console.WriteLine(this.ToString());
}
}
Then Main
static void Main(string[] args)
{
employee e = new employee(1,"","",0);//these values are ignored the way you set this up
e.Print();
Console.ReadLine();
}
Related
Create an Employee class. Items to include as data members are
employee number, name, date of hire, job description, department, and
monthly salary. The class is often used to display an alphabetical
listing of all employees. Include appropriate constructors and
properties. Override the ToString ( ) method to return all data
members. Create a second class to test your Employee class.
I've created an Employee class with the proper variables, properties, and constructors, but am having trouble "testing" it through a second class. The code I have written runs without errors, but doesn't display anything (presumably the goal of the testing). Where am I going wrong in the calling section?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmployeeProgram
{
public class EmployeeProgram
{
private int employeeNumber;
private string name;
private string hiredate;
private int monthlySalary;
private string description;
private string department;
public employee(int employeeNumber, string name, string dateOfHire, int monthlySalary, string description, string department)
{
this.employeeNumber = 456;
this.name = "Joyce";
this.hiredate = "12/15/14";
this.monthlySalary = 3200;
this.description = "Manager";
this.department = "Accounting";
}
public int EmployeeNumber
{
get
{
return employeeNumber;
}
set
{
employeeNumber = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Hiredate
{
get
{
return hiredate;
}
set
{
hiredate = value;
}
}
public int MonthlySalary
{
get
{
return monthlySalary;
}
set
{
monthlySalary = value;
}
}
public string Department
{
get
{
return department;
}
set
{
department = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public override string ToString()
{
return "Employee ID: " + employeeNumber +
"Employee Name: " + name +
"Employee Hire Date: " + hiredate +
"Employee Monthly Salary: " + monthlySalary +
"Employee Description: " + description +
"Employee Department: " + department;
}
public void Print()
{
Console.WriteLine(this.ToString());
}
}
}
From the code you have posted, you don't call Console.WriteLine() anywhere. You have a Print method, but it won't be run until it is called. You need to create an instance of the class, then write the instance's ToString method to the console, or you can call the method Print on the instance.
In main you can do
Employee someone = new Employee(1, "John", "01/01/2016", 5000, "Engineer", "R&D");
Console.WriteLine(someone.ToString());
Console.ReadKey(); // Prevent the console from closing
In your Employee constructor, you should probably use the parameters it asks for, like this
this.employeeNumber = employeeNumber.
You should generally avoid having parameter names that match member variables/properties.
When you don't do anything special in your get and set properties, you can use auto properties
public int EmployeeNumber { get; set; }
My constructor get info from the form. The 'name' is addressed with 'aName' (from the constructor), then there has to be a check done with prop 'NameCheck'. but if I compile it, it return an empty string. Any ideas?
Code:
---- Class ----
//Fields
private List<Create> Characters;
private string name;
private int health;
private int mSpeed;
private Role role;
private Speciality speciality;
//Properties
public string NameCheck
{
get {
return name;
}
set
{
if (string.IsNullOrEmpty(name))
{
name = "Name not specified";
}
else
{
name = value;
}
}
}
//Constructor
public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
this.name = aName;
this.health = aHealth;
this.mSpeed = aMSpeed;
this.role = aRole;
this.speciality = aSpeciality;
Characters = new List<Create>();
}
---- Form ----
Create character = new Create(tbName.Text, health, mspeed, aLane, aSpecial);
Characters.Add(character);
cbSummary.Items.Add(character.ToString());
PS: cbSummary is a combobox.
EDIT:
public override string ToString()
{
return "Name: " + NameCheck + " - Health: " + health + " - MovementSpeed: " + mSpeed + " - Role: " + role + " - Speciality: " + speciality;
}
You should set this.NameCheck instead of this.name in your constructor
public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
this.NameCheck = aName;
also you should check value for emptiness or being null instead of name in your property setter
set
{
if (string.IsNullOrEmpty(value))
{
You have a small typo in your property:
public string NameCheck
{
get {
return name;
}
set
{
// You need to check value, not name.
if (string.IsNullOrEmpty(value))
{
name = "Name not specified";
}
else
{
name = value;
}
}
}
In your constructor you should use your NameCheck property rather than the name field:
public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
this.NameCheck = aName;
this.health = aHealth;
this.mSpeed = aMSpeed;
this.role = aRole;
this.speciality = aSpeciality;
Characters = new List<Create>();
}
Also as Paddy said you are doing an incorrect check in the set body of NameCheck:
public string NameCheck
{
get
{
return name;
}
set
{
if (string.IsNullOrEmpty(value))
{
name = "Name not specified";
}
else
{
name = value;
}
}
}
Have two questions assigned for homework, both of the same form, so I'll post the first one:
"Create an Employee class. Items to include as data members are
employee number, name, date of hire, job description, department, and
monthly salary. The class is often used to display an alphabetical listing of all employees. Include appropriate constructors and properties. Override the
ToString ( ) method to return all data members. Create a second class
to test your Employee class."
I've created an Employee class with the proper variables, properties, and constructors, but am having trouble "testing" it through a second class. The code I have written runs without errors, but doesn't display anything (presumably the goal of the testing). Where am I going wrong in the calling section?
Employee info section:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EmployeeProgram
{
public class employee
{
private int employeeNumber;
private string name;
private string hiredate;
private int monthlySalary;
private string description;
private string department;
public employee(int employeeNumber, string name, string dateOfHire, int monthlySalary, string description, string department)
{
this.employeeNumber = 321;
this.name = "Alex";
this.hiredate = "01/02/15";
this.monthlySalary = 2500;
this.description = "Corporate grunt";
this.department = "Sales";
}
public int EmployeeNumber
{
get
{
return employeeNumber;
}
set
{
employeeNumber = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Hiredate
{
get
{
return hiredate;
}
set
{
hiredate = value;
}
}
public int MonthlySalary
{
get
{
return monthlySalary;
}
set
{
monthlySalary = value;
}
}
public string Department
{
get
{
return department;
}
set
{
department = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public override string ToString()
{
return "Employee ID: " + employeeNumber +
"Employee Name: " + name +
"Employee Hire Date: " + hiredate +
"Employee Monthly Salary: " + monthlySalary +
"Employee Description: " + description +
"Employee Department: " + department;
}
public void Print()
{
Console.WriteLine(this.ToString());
}
}
"Calling section"
namespace employee
{
public class employeeApp
{
public static void Main()
{
EmployeeProgram.employee Employee = new EmployeeProgram.employee(321, "Alex", "1/02/15", 2500, "Corporate grunt", "Sales");
}
}
}
You need to invoke the Print() method of EmployeeProgram.employee in the main() method.
namespace employee
{
public class employeeApp
{
public static void Main()
{
EmployeeProgram.employee Employee = new EmployeeProgram.employee(321, "Alex", "1/02/15", 2500, "Corporate grunt", "Sales");
Employee.Print();
}
}
}
But as others have pointed out, there are a lot of issues with your code:
Class name should be in Pascal casing, i.e., start with a capital letter. Hence, it should be EmployeeProgram.Employee and not EmployeeProgram.employee
Private variables generally follow Camel casing, i.e., start with small letter. Hence, it should be meployee instead of Employee in your Main() method.
You can reduce the boilerplate code in your employee class by making use to auto-properties.
Parameter dateOfHire should be a DateTime object instead of string.
Parameters like monthlySalary are generally of type decimal and not int.
I am new with C# and i have a problem. Actually it's my first year in college and in programming and i have a problem with arrays. I've made a class with 3 constructors and 1 method in Windows Form Application. The problem is that i want to store data from three textBoxes - that the user is typing- into an array of 10 using a button. and i don't know how to do it.
public class Employee
{
private int idnum;
private string flname;
private double annual;
public Employee()
{
idnum = 0;
flname = "";
annual = 0.0;
}
public Employee(int id, string fname)
{
idnum = id;
flname = fname;
annual = 0.0;
}
public Employee(int id, string fname, double ann)
{
idnum = id;
flname = fname;
annual = ann;
}
public int idNumber
{
get { return idnum; }
set { idnum = value; }
}
public string FLName
{
get { return flname; }
set { flname = value; }
}
public double Annual
{
get { return annual; }
set { annual = value; }
}
public string Message()
{
return (Convert.ToString(idnum) + " " + flname + " " + Convert.ToString(annual));
}
}
First of all you should add on this form 3 textboxe elements and name it in a next manner textBoxId, textBoxFLName, textBoxAnnual
Also you have to add a button. Let's call it btnSave
Write an event OnClick for this button. In this method we must read all data which user fill in on the form.
List<Employee> allEmployees = new List<Employee>();
private void buttonSave_Click(object sender, EventArgs e)
{
//read user input
int empId = Int32.Parse(textBoxId.Text);
string empFlName = textBoxFLName.Text;
double empAnnual = double.Parse(textBoxAnnual.Text);
// create new Employee object
Employee emp = new Employee(empId, empFlName, empAnnual);
// add new employee to container (for example array, list, etc).
// In this case I will prefer to use list, becouse it can grow dynamically
allEmployees.Add(emp);
}
And you can also rewrite your code in a little bit shortest manner:
public class Employee
{
public int IdNum { get; set; }
public string FlName { get; set; }
public double Annual { get; set; }
public Employee(int id, string flname, double annual = 0.0)
{
IdNum = id;
FlName = flname;
Annual = annual;
}
public override string ToString()
{
return (Convert.ToString(IdNum) + " " + FlName + " " + Convert.ToString(Annual));
}
}
I was going through code samples of Begining C# 3.0 and followed the sample code along.
When I have created a public/protected method then I was able to access that method using the object of derived class. Ex:
class clsBuilding
{
protected string address { get; set; }
protected Decimal purchasePrice { get; set; }
protected decimal monthlyPayment { get; set; }
protected Decimal taxes { get; set; }
protected decimal insurance { get; set; }
protected DateTime datePurchased { get; set; }
protected int buildingType { get; set; }
public void PropertySummary(string[] desc)
{
desc[0] = "Property Type: "+whichType[buildingType] +
"," + address +
",Cost: " + purchasePrice.ToString("C")+
", Monthly Payment:" + monthlyPayment.ToString("C");
desc[1] = "Insurance: " + insurance.ToString("C") +
" Taxes: " + taxes.ToString("C")+
"Date Purchased: " + datePurchased.ToShortDateString();
desc[2] = "";
}
..............
}
class clsApartment : clsBuilding
{
........................
}
.......
myApt = new clsApartment();
myApt.PropertySummary(desc);
But what is the use of protected property that I have declared at the begining of the parent Class. When I was trying to access them either by using the object of the derived class or directly as instructed in the book:
Just to Drive the point home,given a line in clsBuilding(parent class):
protected decimal purchase price;
you could have the line :
you could have the line purchaseprice = 150000M ; in class home and it would be perfectly acceptable. (Chapter 15,page 447 after 4th paragraph) , neither was a successful on attempt.
I am sure , I must have got the concept wrong or missed something. If not then , why any one would be declaring protected variable or property?
EDIT:
public class clsBuilding
{
//--------------------- Symbolic constants -------------------
public const int APARTMENT = 1;
public const int COMMERCIAL = 2;
public const int HOME = 3;
private string[] whichType = { "", "Apartment", "Commercial", "Home" };
//--------------------- Instance variables -------------------
protected string address;
protected decimal purchasePrice;
protected decimal monthlyPayment;
protected decimal taxes;
protected decimal insurance;
protected DateTime datePurchased;
protected int buildingType;
//--------------------- Constructor --------------------------
public clsBuilding()
{
address = "Not closed yet";
}
public clsBuilding(string addr, decimal price, decimal payment,
decimal tax, decimal insur, DateTime date, int type):this()
{
if (addr.Equals("") == false)
address = addr;
purchasePrice = price;
monthlyPayment = payment;
taxes = tax;
insurance = insur;
datePurchased = date;
buildingType = type;
}
//--------------------- Property Methods ---------------------
public string Address
{
get
{
return address;
}
set
{
if (value.Length != 0)
address = value;
}
}
public decimal PurchasePrice
{
get
{
return purchasePrice;
}
set
{
if (value > 0M)
purchasePrice = value;
}
}
public decimal MonthlyPayment
{
get
{
return monthlyPayment;
}
set
{
if (value > 0M)
monthlyPayment = value;
}
}
public decimal Taxes
{
get
{
return taxes;
}
set
{
if (value > 0M)
taxes = value;
}
}
public decimal Insurance
{
get
{
return insurance;
}
set
{
if (value > 0M)
insurance = value;
}
}
public DateTime DatePurchased
{
get
{
return datePurchased;
}
set
{
if (value.Year > 2008)
datePurchased = value;
}
}
public int BuildingType
{
get
{
return buildingType;
}
set
{
if (value >= APARTMENT && value <= HOME)
buildingType = value;
}
}
//--------------------- General Methods ----------------------
/*****
* Purpose: Provide a basic description of the property
*
* Parameter list:
* string[] desc a string array to hold description
*
* Return value:
* void
*
* CAUTION: Method assumes that there are 3 elements in array
******/
public void PropertySummary(string[] desc)
{
desc[0] = "Property type: " + whichType[buildingType] +
", " + address +
", Cost: " + purchasePrice.ToString("C") +
", Monthly payment: " + monthlyPayment.ToString("C");
desc[1] = " Insurance: " + insurance.ToString("C") + " Taxes: " + taxes.ToString("C") +
" Date purchased: " + datePurchased.ToShortDateString();
desc[2] = " ";
}
/*****
* Purpose: To call someone for snow removal, if available
*
* Parameter list:
* n/a
*
* Return value:
* string
******/
public virtual string RemoveSnow()
{
return whichType[buildingType] + ": No snow removal service available.";
}
}
class clsCommercial : clsBuilding
{
//--------------------- Instance variables -------------------
private int squareFeet;
private int parkingSpaces;
private decimal rentPerSquareFoot;
//--------------------- Constructor --------------------------
public clsCommercial(string addr, decimal price, decimal payment,
decimal tax, decimal insur, DateTime date, int type) :
base(addr, price, payment, tax, insur, date, type)
{
buildingType = type; // Commercial type from base
}
//--------------------- Property Methods ---------------------
public int SquareFeet
{
get
{
return squareFeet;
}
set
{
if (value > 0)
squareFeet = value;
}
}
public int ParkingSpaces
{
get
{
return parkingSpaces;
}
set
{
parkingSpaces = value;
}
}
public decimal RentPerSquareFoot
{
get
{
return rentPerSquareFoot;
}
set
{
if (value > 0M)
rentPerSquareFoot = value;
}
}
//--------------------- General Methods ----------------------
public override string RemoveSnow()
{
return "Commercial: Call Acme Snow Plowing: 803.234.5566";
}
}
public frmMain()
{
InitializeComponent();
myTime = DateTime.Now;
myApt = new clsApartment("123 Ann Dotson Dr., Lexington, KY 40502", 550000, 6000,
15000, 3400, myTime, 1);
myComm = new clsCommercial("4442 Parker Place, York, SC 29745", 1200000, 9000,
22000, 8000, myTime, 2);
myHome = new clsHome("657 Dallas St, Ringgold, GA 30736", 260000, 1100,
1750, 900, myTime, 3);
}
A protected variable/property is accessible from the class and it's derived classes if I remember rightly.
Generally you would use one to prevent the property being publicly accessible to other classes which don't inherit from your class.
Building on what doug said. Protected makes a property, variable, or function available to a subclass, but not from outside the class. If you were to use private, it would still not be accessible from outside the class, nor would it be accessible from it's subclasses.
Protected members can be accessed by other members of the class just like private members. Protected members can also be accessed by members of derived classes. This is the sole difference between private and protected.
In this case the author of clsBuilding intended for the protected properties to be available to any derived classes. It is not a particularly good example without a concrete demonstration of a derived class. Perhaps the details of clsApartment that you omitted contain that demonstration – I certainly hope that is the case.
Here's an artificial example of a situation where you may use protected.
abstract class Preference
{
protected abstract void Load();
protected abstract void Save();
public Preference()
{
Load();
}
~Preference()
{
Save();
}
}
class IntPreference : Preference
{
protected override void Load()
{
//load from registry or config file
}
protected override void Save()
{
//save to registry or config file
}
public int Value { get; set; }
}
class StringPreference : Preference
{
...
}
class FloatPreference : Preference
{
...
}
By making the Load and Save methods protected we can make sure they are not called from outside the Preference class or one of its descendants. But we can call Load and Save from the base class and yet have the actual implementations supplied by derived classes that know how to handle the persistence.
I hope you have covered virtual methods already!