【问题标题】:c# loop until Console.ReadLine = 'y' or 'n'c# 循环直到 Console.ReadLine = 'y' 或 'n'
【发布时间】: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


【解决方案1】:

您可以将输入检查移至循环内部并使用break 退出。请注意,您使用的逻辑将始终评估为 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);

还要注意 ToLower() 之前的空条件运算符 (?.)。这将确保在未输入任何内容时不会抛出 NullReferenceException

【讨论】:

  • 有一些很好的回应,但我认为这是我正在寻找的 - 它最适合基于我试图实现的目标。感谢您的帮助。
【解决方案2】:

如果你想比较一个字符,那么他们不需要ReadLine,你可以使用ReadKey,如果你的条件是:while ((wantCountLower != 'y') || (wantCountLower != 'n'));你的循环将是一个无限循环,所以你可以使用&& 在这里代替||,否则它将是while(wantCount!= 'n'),这样它就会循环直到你按下n

char charYesOrNo;
do
{
   charYesOrNo = Console.ReadKey().KeyChar;
   // do your stuff here
}while(char.ToLower(charYesOrNo) != 'n');

【讨论】:

    猜你喜欢
    • 2012-12-29
    • 2018-04-08
    • 2018-07-13
    • 2019-07-21
    • 2020-12-21
    • 2015-03-11
    • 1970-01-01
    • 2013-08-18
    • 2020-02-23
    相关资源
    最近更新 更多