How do I create a terminable while loop in console

2020-03-30 06:05发布

I am currently looking for a solution for this c# console application function

I tried searching for a method for creating a while loop that can terminate for the code below but I only came up with results relating to breaking while loops or the solution to be not to put it in a while loop


        int P1Choice = int.Parse(Console.ReadLine());

        while (true)
        {
            if (P1Choice == 1)
            {
                Console.WriteLine("");
                CenterWrite("You have chosen Defult Empire 1");
                break;
            }
            if (P1Choice == 2)
            {
                Console.WriteLine("");
                CenterWrite("You have chosen Defult Empire 2");
                break;
            }
            if (P1Choice == 3)
            {
                Console.WriteLine("");
                CenterWrite("You have chosen Defult Empire 3");
                break;
            }
            if (P1Choice == 4)
            {
                Console.WriteLine("");
                CenterWrite("You have chosen Defult Empire 4");
                break;
            }
            else
            {
                Console.WriteLine("");
                CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
                Console.ReadKey();
                int P1Choice = int.Parse(Console.ReadLine());
            }
        }

I understand that I can't declare the local parameter "P1Choice" in this scope, but then are there any other methods to achieve the output of the code in such that when the user doesn't input the corresponding choices, that it loops again?

标签: c#
7条回答
别忘想泡老子
2楼-- · 2020-03-30 06:55

You can do the following

var options = new Dictionary<int, Action> {
{1, () => {
    //opt 1 code
}},
{2, () => {
    //opt 2 code
}},
{3, () => {
    //opt 3 code
}},
{4, () => {
    //opt 4 code
}}
};

Console.WriteLine("Please enter you choice:");

int P1Choice;
while (!(int.TryParse(Console.ReadLine(), out P1Choice) && options.ContainsKey(P1Choice)))
{
    Console.WriteLine("Input Invalid, Please press the number from the corresponding choices to try again:");
}

options[P1Choice]();
查看更多
登录 后发表回答