[英]How do I allow a user to modify a list in my code?
我在我的計算機科學課上有一個作業來創建一個課程列表,向它們添加變量(即名稱、前綴、學分),將這些課程顯示到 cmd 中,然后允許用戶添加或刪除課程。
我已經有了課程列表,但我一直無法編寫正確的代碼來允許用戶從列表中添加或刪除項目。 我可以從用戶那里收集變量以添加課程,但我不知道如何實際使用該數據來創建課程。 這是我的代碼,如果它很亂,我很抱歉; 我不得不玩很多東西來嘗試一些東西,而且我對此也很陌生。
我需要知道如何允許用戶刪除課程或將課程添加到列表中。 我下面的代碼不起作用,無論我輸入什么,它都會在列表中迭代到顯示中。
這是我為刪除項目而編寫的代碼。 它應該將用戶輸入作為整數保存,並將其中繼到將索引位置與整數值對應的 if 語句。
public static void Remove(int index)
{
List<Course> courseList = new List<Course>();
Course c1 = new Course();
Course c2 = new Course(2010, 3, "TCOM", "Technical Writing");
Course c3 = new Course(2345, 3, "Math", "Discrete Mathematics");
Course c4 = new Course(2332, 3, "Math", "Probablility and Data Analysis");
courseList.Add(c1);
courseList.Add(c2);
courseList.Add(c3);
courseList.Add(c4);
courseList.RemoveAt(index);
}
此代碼塊應該添加一門課程。 它適當地向用戶詢問變量並存儲它們,但我不知道如何應用它們並將其添加到列表中。
public static void Add()
{
List<Course> courseList = new List<Course>();
Course c1 = new Course();
Course c2 = new Course(2010, 3, "TCOM", "Technical Writing");
Course c3 = new Course(2345, 3, "Math", "Discrete Mathematics");
Course c4 = new Course(2332, 3, "Math", "Probability and Data Analysis");
courseList.Add(c1);
courseList.Add(c2);
courseList.Add(c3);
courseList.Add(c4);
}
private static void ProcessChoice(int choice)
{
if (choice == 1)
{
Console.WriteLine("Choose a course to delete, with the first course being 0.");
if (choice == 0)
{
Remove(0);
}
if (choice == 1)
{
Remove(1);
}
if (choice == 2)
{
Remove(2);
}
if (choice == 3)
{
Remove(3);
}
if (choice == 4)
{
Remove(4);
}
if (choice == 5)
{
Remove(5);
}
}
if (choice == 2)
{
Console.Write("What is the course number? ");
int coursenum = Int32.Parse(Console.ReadLine());
Console.Write("What is the prefix of your course? ");
string pref = Console.ReadLine();
Console.Write("What is the name of your course? ");
string name = Console.ReadLine();
Console.Write("How many credit hours is the course worth? ");
int crehours = Int32.Parse(Console.ReadLine());
List<Course> courseList = new List<Course>();
Course c5 = new Course(coursenum, crehours, pref, name);
courseList.Add(c5);
Console.WriteLine(); // Once again to add space.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.