While循环。如何循环字符串

时间:2018-10-16 22:21:50

标签: c# loops console console-application

我正在做这个非常简单的测验,我想做的是运行代码并回答问题,并有一个无限循环,最终得到正确答案。
这是我最近完成它的过程,我需要一些帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Media;
using System.Threading.Tasks;

namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("What Countries Capital City is Oslo, Choose From the Following: ");
            Thread.Sleep(5000);
            Console.WriteLine("1.Norway, 2.Sweden, 3.Germany");
            String Answer = Console.ReadLine();

            while (Answer != null)
            {
                if (Answer == "Norway")
                {
                    Console.WriteLine("That is Correct!");
                    Console.Read();
                }
                else if (Answer != "Norway")
                {
                    Console.WriteLine("That is Incorrect!");
                    Console.Read();
                }
            }
        }
    }
}

因此,我使用了while循环,但是如果答案为假,则while循环不会循环,它只会循环一次,但是我需要它无限循环直到答案正确为止。

2 个答案:

答案 0 :(得分:0)

我用调试器运行了代码。

您需要找到“ Console.ReadLine()”和“ Console.Read()”之间的区别。 ->其实我已经从你的错误中学到了。

请不要忘记,在while循环中,“字符串答案”应通过用户输入来重新分配值。

答案 1 :(得分:0)

最简单的解决方案是更改您的while谓词:

while (Answer != "Norway")

您还需要在循环内设置答案变量:

String Answer = String.Empty;

while (Answer != Norway)
{
    Answer = Console.ReadLine();
    if (Answer == "Norway")
    {
        Console.WriteLine("That is Correct!");
    }
    else 
    {
        Console.WriteLine("That is Incorrect!");
    }
}

我删除了Console.Read()语句,因为它们不是必需的。

您可能希望每次用户输入错误的输入时再次打印问题。

通过更改谓词,您还可以使答案不区分大小写:

while (!Answer.Equals("Norway", StringComparison.CurrentCultureIgnoreCase))