Getting a console application to allow input multiple times

我怕爱的太早我们不能终老 提交于 2019-12-11 05:48:07

问题


I made a console application that calculates the number of days since a user-specified date. But after the original calculation, if another date is typed in, the application closes.

Is there a way I can get my application to not close if the user wants to continue using it?

Console.WriteLine("Please enter the date you wish to specify: (DD/MM/YYYY)");
        string userInput;
        userInput = Console.ReadLine();
        DateTime calc = DateTime.Parse(userInput);
        TimeSpan days = DateTime.Now.Subtract(calc);
        Console.WriteLine(days.TotalDays);
        Console.ReadLine();

回答1:


Implement a while loop:

Console.WriteLine("Please enter the date you wish to specify: (DD/MM/YYYY)");
string userInput;
userInput = Console.ReadLine();
while (userInput != "0")
{
    DateTime calc = DateTime.Parse(userInput);
    TimeSpan days = DateTime.Now.Subtract(calc);
    Console.WriteLine(days.TotalDays);
    Console.WriteLine("Add another date");
    userInput = Console.ReadLine();
}

Pressing 0 and enter will exit.




回答2:


Put your code into a loop and let the user have a way to quit the application.

For example

Console.WriteLine("Press q to quit");

bool quitFlag = false;
while (!quitFlag )
{
    Console.WriteLine("Please enter the date you wish to specify: (DD/MM/YYYY)");
    string userInput;
    userInput = Console.ReadLine();
    if (userInput == "q")
    {
        quitFlag = true;
    }
    else
    {
        DateTime calc = DateTime.Parse(userInput);
        TimeSpan days = DateTime.Now.Subtract(calc);
        Console.WriteLine(days.TotalDays);
        Console.ReadLine();
    }
}

This will allow the user to quit the application by entering "q".



来源:https://stackoverflow.com/questions/21118495/getting-a-console-application-to-allow-input-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!