Kli*_*ker 2 c# loops console-application string-comparison while-loop
我对 c# 还很陌生,正在编写一个简单的控制台应用程序作为练习。我希望应用程序提出一个问题,并且只有在用户输入等于“y”或“n”时才进入下一段代码。这是我到目前为止所拥有的。
static void Main(string[] args)
{
string userInput;
do
{
Console.WriteLine("Type something: ");
userInput = Console.ReadLine();
} while (string.IsNullOrEmpty(userInput));
Console.WriteLine("You typed " + userInput);
Console.ReadLine();
string wantCount;
do
{
Console.WriteLine("Do you want me to count the characters present? Yes (y) or No (n): ");
wantCount = Console.ReadLine();
string wantCountLower = wantCount.ToLower();
} while ((wantCountLower != 'y') || (wantCountLower != 'n'));
}
Run Code Online (Sandbox Code Playgroud)
从那string wantCount;以后我就遇到麻烦了。我想要做的是询问用户是否要计算字符串中的字符数,然后循环该问题,直到输入 'y' 或 'n'(不带引号)。
请注意,我还想满足输入的大写/小写的需求,所以我想将 wantCount 字符串转换为小写 - 我知道我目前的方式string wantCountLower在循环内设置时不起作用,所以我然后不能在while 子句中的循环外引用。
你能帮我理解如何实现这个逻辑吗?
您可以将输入检查移动到循环内部并使用 abreak退出。请注意,您使用的逻辑将始终评估为,true因此我已反转条件并将您的char比较更改为string.
string wantCount;
do
{
Console.WriteLine("Do you want me to count the characters present? Yes (y) or No (n): ");
wantCount = Console.ReadLine();
var wantCountLower = wantCount?.ToLower();
if ((wantCountLower == "y") || (wantCountLower == "n"))
break;
} while (true);
Run Code Online (Sandbox Code Playgroud)
还要注意 之前的空条件运算符 ( ?.) ToLower()。这将确保NullReferenceException在没有输入任何内容时不会抛出a 。