向后/前进到C#

时间:2018-10-28 19:51:16

标签: c# if-statement

        Console.WriteLine('What is your name, traveler?');
        string mainName = Console.ReadLine();
        Console.WriteLine('So, your name is ' + mainName + ' ? y/n');
        char ans = Console.ReadKey;
        if (ans == y) 
        {
            Console.WriteLine('Nice, let me introduce myself now.');
        }
        else if(ans == n)
        {

        }
        else
        {
            Console.WriteLine('Please insert either y or n.');
        }

在上面的代码中,如何使else if语句返回第三行,而else语句将返回代码的第一行并从此处继续运行?

1 个答案:

答案 0 :(得分:1)

您可以尝试使用do....While(true)循环

Console.WriteLine("What is your name, traveler?");
string mainName = Console.ReadLine();
Console.WriteLine("So, your name is " + mainName + " ? y/n");
do
{
    var ans = Console.ReadKey(true).Key;
    if (ans == ConsoleKey.Y)
    {
        Console.WriteLine("Nice, let me introduce myself now.");
        break;
    }
    else if (ans == ConsoleKey.N)
    {
        break;
    }
    Console.WriteLine("Please insert either y or n.");
} while (true);

注意

我将使用Console.ReadKey(true).Key来获取键盘输入值,因为它是枚举。