当我输入“设置代码”时,为什么我的代码不能运行?

时间:2014-02-14 23:21:34

标签: c# console console-application readline console.readline

我这里有这个代码:

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

为什么在我输入代码时它没有运行任何其他内容? 我一步一步地调试它,就像在那里休息一样。

2 个答案:

答案 0 :(得分: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()产生一个新的,不同的输入来自用户。

答案 1 :(得分:0)

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

string input = Console.ReadLine();
if (input == "info")