简体   繁体   中英

While loops. How to loop Strings

I am Working on this very simple Quiz, and what I am trying to do is to run the code and answer the question and have an infinite loop which ends in the correct answer.
This is the closest I have come to completing it and I need some help.

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

So I have used a while loop but the while loop does not loop if the answer is false, it only loops once, but I need it to infinitely loop until the answer is correct.

I ran your code with debugger.

you need to find what is different between "Console.ReadLine()" and "Console.Read()". --> Actually I've learn from your mistake.

Please don't forget, in while loop, "String Answer" should be re-assigned value by input of user.

The simplest solution is to alter your while predicate:

while (Answer != "Norway")

You will also need to set your answer variable inside the loop:

String Answer = String.Empty;

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

I have removed the Console.Read() statements as they aren't necessary.

You may wish to print the question again each time the user enters the wrong input.

You could also make the answer case-insensitive, by changing the predicate thus:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM