How to loop a Console.ReadLine?

后端 未结 5 2002
醉酒成梦
醉酒成梦 2021-01-06 13:31

I cannot figure out how to read user-input in a loop (with Console.ReadLine). I\'m trying to create a note that lets me store what ever the user inputs, and exi

5条回答
  •  太阳男子
    2021-01-06 13:52

    One way to do it is this:

    List simpleList = new List { "Alpha", "Bravo", "Charlie", "Delta", "Echo" }; //Dummy data source
            Console.WriteLine("Enter a call sign to find in the list. Press X to exit: "); //Prompt
    
            string callSign;
            string exitKey = "x";
    
            while ((callSign = Console.ReadLine()) != exitKey.ToLower()) { //This is where the "Magic" happens
                if (simpleList.Contains(callSign)) {
                    Console.WriteLine($"\"{callSign}\" exists in our simple list");//Output should the list contain our entry
                    Console.WriteLine(""); //Not really relevant, just needed to added spacing between input and output
                }
                else {
                    Console.WriteLine($"\"{callSign}\" does not exist in our simple list"); //Output should the list not contain our entry
                }
                Console.WriteLine("");
                Console.WriteLine("Enter a call sign to find in the list. Press X to exit: ");//Prompt
            }
    

    The line:

    while ((callSign = Console.ReadLine()) != exitKey.ToLower()) {
          ...
    

    is where the loop happens. If the entry does not equal the exitKey, the steps are repeated.

提交回复
热议问题