0

我在这里有这段代码:

    string code1 = null;
    Console.Write("Username: " + Environment.UserName.ToString() + ">");
    if (Console.ReadLine() == "info")
    {
        Console.WriteLine("Info:");
    }
    else if (Console.ReadLine() == "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
    {
        string temp = Console.ReadLine();
        Console.WriteLine("'" + temp + "' is not known as a command \nEnter 'info' to view all commands");
    }
    Console.ReadLine();

当我输入“设置代码”时,它什么也不做,然后当我输入诸如信息之类的东西时,它会转到string temp = Console.ReadLine();但随后它不会运行Console.WriteLine("'" + temp + "' is not known as a command \nEnter 'info' to view all commands");

为什么当我输入该代码时它不运行其他任何东西?我一步一步调试它,它就像在那里休息一样。

4

2 回答 2

3

因为“设置代码”只能作为第二个输入的输入,如果只有第一个输入不是“信息”......

尝试这个:

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

您只需执行一次 ReadLine() 即可从用户那里获取一行,然后在该行上进行比较,而不是在新的 ReadLine() 上进行比较,因为您所做的每个 ReadLine() 都会从用户那里产生一个新的、不同的输入.

于 2014-02-14T23:30:29.210 回答
0

因为每次你打电话Console.ReadLine()你都会得到一个新的输入。如果你写"Set Code"你的第一个 if 语句将被传递,但是在你的 else if 语句中你Console.ReadLine再次调用,并且 else if会在你输入后检查你的新输入,而不是第一个。首先获取输入并存储到变量中,然后在 if - elseif 语句中使用该变量:

string input = Console.ReadLine();
if (input == "info")
于 2014-02-14T23:33:39.210 回答