如何在C#中获取程序以响应用户输入

时间:2018-09-19 12:59:30

标签: c# while-loop readline

所以下面是我的代码。当我按5时,我必须按Enter 5次才能使程序编写该行,按6根本不起作用。任何解决方案将不胜感激。

            Boolean keepRunning = true;
            while (keepRunning = true)
            {
                if (Console.ReadLine() == "1")
                {
                    Console.WriteLine("Still running");
                }
                else if (Console.ReadLine() == "2")
                {
                    Console.WriteLine("Still running2");
                }
                else if (Console.ReadLine() == "3")
                {
                    Console.WriteLine("Still running3");
                }
                else if (Console.ReadLine() == "4")
                {
                    Console.WriteLine("Still running4");
                }
                else if (Console.ReadLine() == "5")
                {
                    Console.WriteLine("Still running5");
                }
                else if (Console.ReadLine() == "6")
                {
                    keepRunning = false;
                }
            }

2 个答案:

答案 0 :(得分:8)

您正在等待每个Console.ReadLine();的输入。仅读取一次输入,然后决定要做什么。

您应该将while条件更改为keepRunning == true。在您当前的版本中,您将keepRunning设置为true,这就是为什么看起来“ 6”无法正常工作的原因;)

Boolean keepRunning = true;
while (keepRunning == true)
{
    string input = Console.ReadLine();

    if (input == "1")
    {
        Console.WriteLine("Still running");
    }
    else if (input == "2")
    {
        Console.WriteLine("Still running2");
    }
    else if (input == "3")
    {
        Console.WriteLine("Still running3");
    }
    else if (input == "4")
    {
        Console.WriteLine("Still running4");
    }
    else if (input == "5")
    {
        Console.WriteLine("Still running5");
    }
    else if (input == "6")
    {
        keepRunning = false;
    }
}

您可以使用switch语句使其变得更好。

switch(input)
{
    case "1":
        Console.WriteLine("Still running");
        break;
    case "2":
        Console.WriteLine("Still running");
        break;
    case "3":
        Console.WriteLine("Still running");
        break;
    case "4":
        Console.WriteLine("Still running");
        break;
    case "5":
        Console.WriteLine("Still running");
        break;
    case "6":
        keepRunning = false;
        break;
    default:
        break;
}

答案 1 :(得分:0)

每次迭代您只能读取一次行。请参见下面的示例:

string readLine = "";
Boolean keepRunning = true;
while (keepRunning)
{
    readLine= Console.ReadLine();
    switch readLine{
        case "1":
            Console.WriteLine("Still running");
            break;
        case "2":
            Console.WriteLine("Still running2");
            break;
        case "3":
            Console.WriteLine("Still running3");
            break;
        case "4":
            Console.WriteLine("Still running4");
            break;
        case "5":
            Console.WriteLine("Still running5");
            break;
        case "6":
            keepRunning = false;
            break;
    }
}