使用Switch语句在C#中循环

时间:2017-11-12 16:18:24

标签: c# if-statement while-loop

如果选择超出范围,我试图循环切换条件。但我没有得到理想的输出。因此,如果在经历切换条件时用户没有输入1-3作为输入,我希望它进入默认条件,该条件应触发错误语句然后继续循环

Console.WriteLine("Which book would you like to check out?");
Console.WriteLine("select 1 for book 1, 2 for book 2, and 3 for book 3");

int choice=Convert.ToInt32(Console.ReadLine());

bool loopBreak = true;
while (true)
{
    switch (choice)
    {

        case 1:
            Console.WriteLine("You have chosen book 1 {0}", b1.name);
            b1.CheckinCheckout = false;

            break;


        case 2:
            Console.WriteLine("You have chosen book 2 {0}", b2.name);
            b2.CheckinCheckout = false;

            break;

        case 3:
            Console.WriteLine("You have chosen book 3 {0}", b3.name);
            b3.CheckinCheckout = false;

            break;
        default:
            Console.WriteLine("Please enter a valid choice.");
            loopBreak = false;
            break;
    }
    if (loopBreak != false)
    {

        break;
    }
}

更新:

bool loopBreak=true;
while (loopBreak==true)
{
    Console.WriteLine("Which book would you like to check out?");
    Console.WriteLine("select 1 for book 1, 2 for book 2, and 3 for book 3");
    int choice = Convert.ToInt32(Console.ReadLine());
    switch (choice)
    {

        case 1:
            Console.WriteLine("You have chosen book 1 {0}", b1.name);
            b1.CheckinCheckout = false;

            break;


        case 2:
            Console.WriteLine("You have chosen book 2 {0}", b2.name);
            b2.CheckinCheckout = false;

            break;

        case 3:
            Console.WriteLine("You have chosen book 3 {0}", b3.name);
            b3.CheckinCheckout = false;

            break;
        default:
            Console.WriteLine("Please enter a valid choice.");
            loopBreak = false;
            break;
    }
    break;
}

1 个答案:

答案 0 :(得分:2)

当您想要退出循环时,需要将布尔值设置为false,并且当您想要继续请求有效输入时,不需要执行任何操作。

loopContinue = true;
while (loopContinue)
{
    Console.WriteLine("Which book would you like to check out?");
    Console.WriteLine("select 1 for book 1, 2 for book 2, and 3 for book 3");
    // Use TryParse when reading the user input. This will avoid an 
    // Exception if the user types a letter for example.
    if(Int32.TryParse(Console.ReadLine(), int out choice)
    {
        switch (choice)
        {
            case 1:
               ....
               loopContinue = false;
               break;
            case 2:
               ....
               loopContinue = false;
               break;
            case 3:
               ....
               loopContinue = false;
               break;

            // not really needed, if you remove the default
            // then your loop will not exit and you can start again
            default:
               loopContinue = true;
               break;
    }
    if(loopContinue)
         Console.WriteLine("Please enter a valid choice.");
}