請有人幫助我如何找到代碼中的錯誤。我無法使用 switch 運算子將員工添加到陣列串列中。Тhe 代碼沒有顯示任何錯誤,但無法正常作業,并且陣列未填充任何內容提前謝謝!
class Program { class Employee : IComparable { 私有字串名稱;私有整數級別;私人日期時間招聘日期;
public Employee(string name, int level, DateTime hiringDate)
{
this.name = name;
this.level = level;
this.hiringDate = hiringDate;
}
public string Name
{
get { return name; }
set { this.name = value; }
}
public int Level
{
get { return level; }
set { this.level = value; }
}
public DateTime HiringDate
{
get { return hiringDate; }
set { this.hiringDate = value; }
}
public int CompareTo(object obj)
{
if(obj == null)
{
return 1;
}
Employee other = obj as Employee;
int value = this.level.CompareTo(other.level);
if(value == 0)
{
value = this.hiringDate.CompareTo(other.hiringDate);
}
return value;
}
public void Description()
{
Console.WriteLine("Name: {0}, Level: {1}, Hiring Date: {2}", name, level, hiringDate.ToString());
}
}
static void Main(string[] args)
{
bool exit = false;
ArrayList employees = new ArrayList();
string name;
int level, pos;
Employee mostExp;
DateTime hiringDate;
while (!exit)
{
Console.WriteLine("---------------MENU!---------------");
Console.WriteLine("1. Display employees by level.");
Console.WriteLine("2. Add new employee to list.");
Console.WriteLine("3. Remove employee from list.");
Console.WriteLine("4. Search for employee by name.");
Console.WriteLine("5. Get employee with most work expirience. ");
Console.WriteLine("6. Exit!");
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
employees.Sort();
Console.WriteLine("----------------------------------");
foreach (Employee employee in employees)
{
employee.Description();
}
Console.WriteLine("----------------------------------");
break;
case 2:
Console.WriteLine("Enter employee name: ");
name = Console.ReadLine();
Console.WriteLine("Enter employee level: ");
level= int.Parse(Console.ReadLine());
Console.WriteLine("Enter hiring date 'yyyy-mm-dd': ");
hiringDate = DateTime.Parse(Console.ReadLine());
break;
case 3:
Console.WriteLine("Delete employee at position: ");
pos = int.Parse(Console.ReadLine());
employees.RemoveAt(pos);
break;
case 4:
Console.WriteLine("Enter employee name: ");
name = Console.ReadLine();
Console.WriteLine("----------------------------------");
foreach (Employee employee in employees)
{
if (employee.Name == name)
{
employee.Description();
}
}
Console.WriteLine("----------------------------------");
break;
case 5:
mostExp = (Employee)employees[0];
foreach (Employee employee in employees)
{
if(mostExp.HiringDate.CompareTo(employee.HiringDate) == 1)
{
mostExp = employee;
}
}
Console.WriteLine("Employee with most work expirience:");
mostExp.Description();
break;
default:
return;
}
}
}
}
}
uj5u.com熱心網友回復:
在 switch case 中,您正在從命令列讀取某些值,并將它們存盤在一些區域變數(名稱、級別、招聘日期)中,但您根本沒有創建 Employee 物件:) Employee emp = Employee(name, level, hiringdate。然后您必須將該員工添加到 ArrayList: employees.add(emp)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/371207.html
下一篇:類中方法的類裝飾器
