【发布时间】:2022-01-29 01:01:35
【问题描述】:
新手在这里学习c#。我有一个关于保存用户输入的问题。 我有两种方法,主要方法和汽车方法。在汽车方法中,我有一个列表,其中已经包含三辆汽车。在汽车方法中,用户可以选择将新车添加到列表中或打印出该列表中的所有汽车。 添加新车并选择打印列表后,程序会显示所有汽车,包括新添加的汽车。 但是在 main 方法中返回菜单然后再次进入 car 方法时,列表被重置为仅保存从开始放入列表中的三辆汽车。有没有办法实际保存用户的输入,将其存储在列表或其他东西中,然后能够访问它以将其打印出来?如前所述,我在这里是一个完全的初学者,所以我希望我是有道理的,并且真的会应用所有的反馈和提示!谢谢。
using System;
using System.Collections.Generic;
class Program{
public static void Main(string [] args){
int menuSelect = 0;
do{
// Printing menu options and taking user input
Console.WriteLine("1. Cars " + "\n2. Exit");
Console.WriteLine("Enter a option: ");
menuSelect = Convert.ToInt32(Console.ReadLine());
// Go to Cars method
if(menuSelect == 1){
Cars();
// Message to user if input is higher than menu allows
} else if (menuSelect > 2){
Console.WriteLine("\nInvalid Choise");
}
}while(menuSelect != 2);
Console.WriteLine("\nPress 'Enter' to exit...");
Console.ReadLine();
}
public static void Cars(){
// List containing cars. Resets every time entering the method to
// just BMW, Volvo and Fiat. Regardless if the user has added a new car.
List <string> carList = new List <string> {"BMW", "Volvo", "Fiat"};
int carMenuSelect = 0;
do{
// Printing menu and taking user input
Console.WriteLine("1. Add Car" + "\n2. Show Cars" + "\n3. Exit");
Console.WriteLine("Enter a option: ");
carMenuSelect = Convert.ToInt32(Console.ReadLine());
// Lets the user add a new car to the list
if (carMenuSelect == 1){
Console.WriteLine("Enter new car: ");
string newCar = Console.ReadLine();
Console.WriteLine("New Car Added!");
carList.Add(newCar);
} else if(carMenuSelect == 2){
foreach (string car in carList){
Console.WriteLine(car);
}
} else if(carMenuSelect > 3){
Console.WriteLine("\nInvalid option...");
}
}while(carMenuSelect != 3);
Console.WriteLine("Press 'Enter' to return to menu....");
Console.ReadLine();
}
}
【问题讨论】: