c# - 怎么获得 !运算符在具有多个条件的 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# 中是不可变的,所以这样做:
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");
}
我在这里做了一个小提琴
推荐阅读
- kubernetes - Google Kubernetes Engine - Prometheus 和 Grafana 的 Ingress 无法正常工作
- docker - 安装 docker 桌面后 postgre 无法将主机名“xxxx.xxxxxxx.xxx”转换为地址:nodename nor servname provided, or not known”
- java - 对数据库会话上下文的更改通过池连接重用持续存在
- javascript - fullcalendar v5 - 单击 daygrid 顶部的图标时打开模式
- r - 如何去除异常值但保留 NA
- javascript - 如何在不更改内容的情况下更改日期的时区?
- c# - 何时使用 Xamarin 绑定而不是将对象传递给页面构造函数?
- json - 如何解析 twilio 通知 API 请求响应
- php - 如何在 PHP MySql 中根据用户角色检索数据
- mongodb - 从 MongoDB 中的文档数组创建字符串数组