【问题标题】:C# The "while" should break after someone put the correct answer in but it doesntC#“while”应该在有人输入正确答案后中断,但它没有
【发布时间】:2019-12-13 19:48:18
【问题描述】:

我真的是编程新手,这实际上是我的第一个程序,但我现在被这个问题困扰了一天。 while 一直在重复同样的方法,letter1 == correct1 与否都没有关系。

class Program
    {
        static void Main(string[] args)
        {    
            string try1;
            char correct1 = 'o';
            string try2;
            string correct2 = "r";
            string try3;
            string correct3 = "a";
            string try4;
            string correct4 = "n";
            string try5;
            string correct5 = "g";
            string try6;
            string correct6 = "e";

            int live = 9;
            int letter = 6;

            Console.WriteLine("Hanging man");
            try1 = Console.ReadLine();
            char letter1 = try1[0];

            while ( letter1 != correct1 ||
                    try1 != correct2 || 
                    try1 != correct3 || 
                    try1 != correct4 || 
                    try1 != correct5 || 
                    try1 != correct6)
            {
                live--;
                Console.WriteLine("Schade leider ist der buchstabe " +
                                      try1 + " nicht dabei du hast noch " +
                                      live + " Leben ");
                Console.WriteLine("Versuch es erneut");
                try1 = Console.ReadLine();
            }
            Console.WriteLine("Test");

【问题讨论】:

  • try1 != correct2 || try1 != correct3 || try1 != correct4 || try1 != correct5 || try1 != correct6 将始终评估为真。您的字符串不可能同时具有所有这些值。您想使用逻辑 AND &&
  • 您想使用 do...while,并带有布尔“继续”变量。这几乎就是我将如何执行每个“重复输入直到用户开始理解”例程的方式。这种情况对于单个代码行来说太复杂了。
  • true || true || falsetrue || false || truefalse || true || true 都评估为 true
  • 当您发现自己使用 6 个变量并或多或少以相同的方式处理它们时,开始考虑使用集合(例如 List<string>List <char> 在您的情况下):代码将简化很多.另请注意:correct1char 和其他 correctX 是字符串(为什么?)并且您根本没有使用 try2...n

标签: c# loops while-loop


【解决方案1】:

布尔代数:!(a || b) 等于 !a && !b。 试试这个:

while ( letter1 != correct1 && try1 != correct2 && try1 != correct3 && try1 != correct4 && try1 != correct5 && try1 != correct6)

【讨论】:

  • “布尔代数:!(a || b) 等于!a && !b”与这个问题有什么关系?我知道这与 OP 的问题很接近,但这不是这里发生的事情。
  • @Enigmativity 当任何一对相等时,循环应该中断。所以编写循环的一种方法是说while (!(a==x || b==x || ...),相当于while (a!=x && b !=x && ...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
  • 2014-01-30
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多