卡在无限的 if 循环上

本文关键字:循环 if 无限 | 更新日期: 2023-09-27 18:19:55

我正在为Visual Studio 2015中的班级开发一个c#控制台骰子模拟实验室。我根据用户的响应将程序分解为三个 if 循环。如果用户没有输入有效的响应,我有一个专用的 do while 循环。由于某种原因,我被困在那个循环中,无法出去。最重要的是,由于它是告诉用户输入有效的响应,所以它是第一个if语句。因此,即使我输入"y"、"Y"、"n"或"N",它仍然会初始化。这是有问题的部分。

        // get response from user
        response = ReadLine();
        // loop starts if user does not reply with valid response in order to retrieve a valid response
        if (response != "N" || response != "Y" || response != "n" || response != "y")
        {
            do
            {
                WriteLine("Please reply with Y or N");
                response = ReadLine();
            }
            while (response != "N" || response != "Y" || response != "n" || response != "y");
        }

我正在使用 or 运算符,所以我不明白为什么它会以这种方式循环。

卡在无限的 if 循环上

response != "N" || response != "Y" || response != "n" || response != "y"

应该是

response != "N" && response != "Y" && response != "n" && response != "y"

因为如果您点击其中一个有效响应,您应该退出循环

你需要使用 && 而不是 ||

response != "N" && response != "Y" && response != "n" && response != "y"

行为不端的直接原因是错误的布尔运算符,你想要&& ||的插入;您还可以将ifdo..while组合成while..do

response = Console.ReadLine();
while (response != "N" && response != "Y" && response != "n" && response != "y") {
  WriteLine("Please reply with Y or N");
  response = Console.ReadLine();
}

下一步是将所有可能的响应放入集合中:

  Dictionary<String, Boolean> expectedResponses = new Dictionary<String, Boolean>() {
    {"Y", true},
    {"y", true},
    {"N", false},
    {"n", false},
  };
  ...
  response = Console.ReadLine();
  while (!expectedResponses.ContainsKey(response)) {
    WriteLine("Please reply with Y or N");
    response = Console.ReadLine();
  }
  ...
  if (expectedResponses[response]) {
    // user said "yes"
  }
  else {
    // user said "no"
  } 

你的代码应该是这样的,尽量用 && 代替 ||。

    response = ReadLine();
    // loop starts if user does not reply with valid response in order to retrieve a valid response
    if (response != "N" && response != "Y" && response != "n" && response != "y")
    {
        do
        {
            WriteLine("Please reply with Y or N");
            response = ReadLine();
        }
        while (response != "N" && response != "Y" && response != "n" && response != "y");
    }

如果很难想象

response != "N" || response != "Y" || response != "n" || response != "y"

使用德摩根定律展开。 将!=替换为==||替换为&&。 在表达式前加上!

!(response == "N" && response == "Y" && response == "n" && response == "y")

现在,您会看到响应必须等于 NY,同时ny。因此,在它使它永远为真之前,它总是错误的陈述和否定。

所以现在你明白你应该用OR代替AND.然后使用德摩根定律再次简化。

!(response == "N" || response == "Y" || response == "n" || response == "y") <=>
response != "N" && response != "Y" && response != "n" && response != "y"