坚持无限的if循环

时间:2015-10-30 06:22:49

标签: c#

我正在为Visual Studio 2015中的班级开发一个c#console dice sim lab。我根据用户的响应将我的程序分成三个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运算符,所以我不明白为什么它循环的方式。

5 个答案:

答案 0 :(得分:2)

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

应该是

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

因为如果你点击其中一个有效的回复,你应该退出循环

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

错误行为的直接原因是错误的布尔运算符,您希望&&不是||; 您还可以将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"
  } 

答案 3 :(得分:0)

您的代码应该是这样的,尝试使用&amp;&amp;而不是||。

    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");
    }

答案 4 :(得分:0)

如果难以想象

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

使用德摩根定律进行扩展。将!=替换为==。和||&&。在表达之前加上!

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

现在您看到响应必须同时等同于NY以及ny。因此,它始终是错误的陈述和否定使它永远成真。

所以现在你明白你应该把OR而不是AND。然后再使用demorgan法进行简化。

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