C# Restarting a console application

瘦欲@ 提交于 2019-12-20 03:52:30

问题


I've created a small application that does a small conversion. At the end of the program I've created a method that allows the user to make another calculation if they press 'r'. All I want it to do is if they press r, take them back to the beginning of Main, else terminate program. I do not want to use goto. This is what I've got so far, and the error I'm getting.

http://puu.sh/juBWP/c7c3f7be61.png


回答1:


A while loop would be a good fit, but since you say the program should run and then give the user the option to run again, an even better loop would be a Do While. The difference between while and Do While is that Do While will always run at least once.

        string inputStr;

        do
        {
            RunProgram();

            Console.WriteLine("Run again?");
            inputStr = Console.ReadLine();
        } while (inputStr == "y");

        TerminateProgram();



回答2:


I recommend you use another function instead of Main(). Please refer to the code below:

    static void Main(string[] args)
    {
        doSomething();
    }

    public static void WouldYouLikeToRestart()
    {
        Console.WriteLine("Press r to restart");
        ConsoleKeyInfo input = Console.ReadKey();
        Console.WriteLine();

        if (input.KeyChar == 'r')
        {
            doSomething();
        }
    }

    public static void doSomething()
    {
        Console.WriteLine("Do Something");
        WouldYouLikeToRestart();
    }



回答3:


In your case, you want to repeat something so of course you should use a while loop. Use a while loop to wrap all your code up like this:

while (true) {
    //all your code in the main method.
}

And then you prompt the user to enter 'r' at the end of the loop:

if (Console.ReadLine () != "r") {//this is just an example, you can use whatever method to get the input
    break;
}

If the user enters r then the loop continues to do the work. break means to stop executing the stuff in the loop.



来源:https://stackoverflow.com/questions/31900676/c-sharp-restarting-a-console-application

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