我在計算機科學課上創建了一個課程列表,爲他們添加變量(即姓名,前綴,學分),將這些課程顯示給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.
}
問題是您的功能不共享數據。您的列表範圍在方法(功能)級別上,而不是在級別級別上(功能之間共享)。看看:https://msdn.microsoft.com/en-us/library/ms173118.aspx – David
也刪除課程項目的索引可能會崩潰您的程序 – Steve
' if(choice == 1) {... if(choice == 0) {'你將永遠不會得到這個選擇== 0或其他任何東西,但== 1 –