首页 > 解决方案 > 怎么获得 !运算符在具有多个条件的 while 循环内工作

问题描述

我尝试使用 while 循环进行检查我希望循环仅在触发三个条件之一时要求用户重新输入其值。也就是说,如果响应是空白的,也不是“Y”或“N”。我通过使用 ! 操作员。我注意到即使响应是正确的选择,while 循环仍然要求重新输入一个值。我还注意到,当我删除 ! 从第二个条件前面的运算符和用户输入正确的响应代码后循环块工作,但当我添加!即使响应正确,操作员也会返回到循环工作的条件。

PromptMessage("If you are using a different download path for your mods enter (Y)es. Or if you want to exit out the" +
                " program enter (N)o!", ConsoleColor.Green);
string CustomPath = Console.ReadLine();
CustomPath.ToUpper();
Console.WriteLine(CustomPath);
while (!CustomPath.Contains("Y") || !CustomPath.Contains("N") || String.IsNullOrEmpty(CustomPath))
{
    AlertMessage("Please enter either Y to continue or N to exit");                    
    CustomPath = Console.ReadLine();
    CustomPath.ToUpper();                   
}

标签: c#

解决方案


你这里有几件事不对。首先,字符串在 C# 中是不可变的,所以这样做:

string foo = "some string";
foo.ToUpper();

意味着运行它之后foo仍然等于。"some string"您需要将值分配给一个变量(它甚至可以是同一个变量)。像这样:

string foo = "some string";
foo = foo.ToUpper();
//foo = "SOME STRING"

下一个问题是你的循环和逻辑。我认为更简单的方法是使用do/while循环并检查 while 条件中输入的“有效性”。循环意味着你总是会在检查条件do/while之前“做”一次。while你总是想要求输入一次,所以使用这个循环更有意义:

public static void Main()
{
    //defined in outer scope        
    string customPath = string.Empty;
    do
    {
        Console.WriteLine("If you are using a different download path for your mods enter (Y)es. Or if you want to exit out the program enter (N)o!");
        //Calling ToUpper() before assigning the value to customPath
        customPath = Console.ReadLine().ToUpper();
    }
    while (customPath != "N" && customPath != "Y");
}

我在这里做了一个小提琴


推荐阅读