为什么我的程序在第二次输入内容后关闭

时间:2014-02-14 23:44:02

标签: c# console console-application

我这里有这个代码:

    string code1 = null;
    Console.Write("Username: " + Environment.UserName.ToString() + ">");
    string line = Console.ReadLine();
    if (line == "info")
    {
        Console.WriteLine("Info:");
    }
    else if (line == "Set Code")
    {
        if (code1 == null)
        {
            Console.Write("TEST");
        }
        else
        {
            Console.WriteLine("'Set Code' is not known as a command \nEnter 'info' to view all commands");
            Console.Write("Username: " + Environment.UserName.ToString() + ">");
        }
    }
    else
    {
        Console.WriteLine("'" + line + "' is not known as a command \nEnter 'info' to view all commands");
    }
    Console.ReadLine();

当我输入内容时,如“null”,它将运行else代码。如果我尝试再次输入内容,则会关闭控制台。为什么这样做?

2 个答案:

答案 0 :(得分:3)

如果要将代码放入while循环中,它将不会关闭。这是编辑过的代码:

string code1 = null;
while(true)
{
    Console.Write("Username: " + Environment.UserName.ToString() + ">");
    string line = Console.ReadLine();
    if (line == "info")
    {
        Console.WriteLine("Info:");
    }
    else if (line == "Set Code")
    {
        if (code1 == null)
        {
            Console.Write("TEST");
        }
        else
        {
            Console.WriteLine("'Set Code' is not known as a command \nEnter 'info' to view all commands");
            Console.Write("Username: " + Environment.UserName.ToString() + ">");
        }
    }
    else if (line == "quit")
    {
        break;
    }
    else
    {
        Console.WriteLine("'" + line + "' is not known as a command \nEnter 'info' to view all commands");
    }
}

答案 1 :(得分:0)

您注意到的第一个ReadLine()将等待用户输入。您键入“null”并进入

else
{
    Console.WriteLine("'" + line + "' is not known as a command \nEnter 'info' to view all commands");
}

控制流程。

当你到达第二个ReadLine()时,你可以输入任何内容,但是当你这样做并输入回车时,该程序没有别的办法可以退出。

如果你想要一个永无止境的输入,你应该尝试做一个循环。