【发布时间】:2017-01-12 09:31:35
【问题描述】:
我对 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'));
}
从string wantCount; 开始,我遇到了麻烦。我想要做的是询问用户是否要计算字符串中的字符,然后循环该问题,直到输入“y”或“n”(不带引号)。
请注意,我还想适应输入的大写/小写字母,所以我想将 wantCount 字符串转换为小写 - 我知道我目前的设置将无法工作,因为我正在设置 string wantCountLower在循环内,所以我不能在 while 子句中引用循环外。
你能帮我理解如何实现这个逻辑吗?
【问题讨论】:
-
wantCountLower在 do-while 范围内定义,因此在外部不可用。您需要在循环之前定义它(或者更好的是,使用不区分大小写的比较)。 -
我认为您需要正确阅读 while 语法的工作原理
-
'y'是您需要"y"来检查字符串的字符的表示法。 -
prof1990,感谢您指出使用不正确的标点符号。 Takarii,你完全正确 - 正如我所提到的,我仍然是新手,但这是我首选的学习方法。 Luaan,我想这样做,但不确定是否可以为其分配一个有效值,因为 wantCount 在循环内分配了一个值。
标签: c# loops while-loop console-application string-comparison