我试图使用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#中是不可变的,所以这样做:
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");
}
我在这里做了一把小提琴
我认为您的逻辑可能颠倒了。你的意思是说while
的条件如下吗?
while (!CustomPath.Contains("Y") && !CustomPath.Contains("N") && !String.IsNullOrEmpty(CustomPath))
这在逻辑上等同于以下语句(但这一语句的可读性要差得多(
while (!(CustomPath.Contains("Y") || CustomPath.Contains("N") || String.IsNullOrEmpty(CustomPath))
这样,当输入的路径不包含"Y"、"N"或空路径时,循环将继续。
另外请注意,正如@maccettura所指出的,您将希望更改为使用CustomPath = CustomPath.ToUpper();
更改到此
while ((!CustomPath.Contains("Y") && !CustomPath.Contains("N")) || String.IsNullOrEmpty(CustomPath))
我意识到您的代码将永远返回true。
例如,您输入"Y">
!CustomPath.Contains("Y") => false
!CustomPath.Contains("N") => true
由于使用了||
,因此它将始终返回true。