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.
- Please post code as text (properly formatted) - link to image on random site is not really welcome on SO and additionally it can disappear and render the post completely useless for future readers.Alexei Levenkov– Alexei Levenkov2015-08-09 04:38:45 +00:00Commented Aug 9, 2015 at 4:38
3 Answers
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(); } 1 Comment
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(); Comments
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.