c#while循环中断

时间:2017-06-12 19:26:45

标签: c# while-loop

我想知道是否有人可以帮助我。我是编程新手,这是我第一次使用stackoverflow。

我正在寻找创建一个while循环,询问用户的背景,一旦输入正确就可以突破循环。我可以用break来退出,但我试图找到另一种方式。到目前为止我的代码是:

var background = "";

while (background != "M" || background != "W" || background != "R")
{ 
    Console.WriteLine("Welcome " + name + ", " + "Please pick a class: \n" +
                              "(M)age \n" +
                              "(W)arrior \n" +
                              "(R)ogue \n");
    var readLine = Console.ReadLine();
    if (readLine != null) background = readLine.ToUpper();

    if (background == "M")
    {
        Console.WriteLine("Welcome Mage " + name);            
    }
    else if (background == "W")
    {
        Console.WriteLine("Welcome Warrior " + name);                    
    }
    else if (background == "R")
    {
        Console.WriteLine("Welcome Rogue " + name);
    }
    else
    {
        Console.WriteLine("Invalid choice"); 
    }
}

3 个答案:

答案 0 :(得分:5)

“||”是“或”。您的while表达式将始终为真,因为背景不是“M”,总是正确的,它不是“W”,它是不是“R”。

使用“或”,所有三个检查都必须为false,因为整个表达式都是假的,但至少有两个“!=”子表达式必须始终为真。如果background为“M”,则不能为“W”或“R”。

    while (background != "M" || background != "W" || background != "R")

你想要的是“&amp;&amp;”,意思是“和”:你想继续循环,而背景不是“M”背景不是“W”等。< / p>

    while (background != "M" && background != "W" && background != "R")

答案 1 :(得分:0)

使用'flag'指定循环是否应该中断将适用于您的情况。

var background = "";
bool breakLoop = false;

    while (!breakLoop)
    { 
        Console.WriteLine("Welcome " + name + ", " + "Please pick a class: \n" +
                          "(M)age \n" +
                          "(W)arrior \n" +
                          "(R)ogue \n");
        var readLine = Console.ReadLine();
        if (readLine != null) background = readLine.ToUpper();

        if (background == "M")
        {
            Console.WriteLine("Welcome Mage " + name);
            breakLoop = true;
        }

        else if (background == "W")
        {
            Console.WriteLine("Welcome Warrior " + name);
            breakLoop = true;
        }

        else if (background == "R")
        {
            Console.WriteLine("Welcome Rogue " + name);
            breakLoop = true;
        }

        else
            Console.WriteLine("Invalid choice"); 
    }

答案 2 :(得分:0)

我个人想创建一个已接受的回复列表,并检查用户输入是否在该列表中。

var name = "Bob";
var validTypes = new List<string> {"M", "W", "R"};
while (true)
{
    Console.WriteLine($"Welcome {name}, please pick a class" +
                       "\n(M)age" +
                       "\n(W)arrior" +
                       "\n(R)ogue" +
                       "\n");
    var charType = Console.ReadLine();

    if (validTypes.Contains(charType.ToUpper()))
    {
        break;
    }
    else
    {
        Console.WriteLine("Please enter a valid class letter");
    }