2

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
  • 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. Commented Aug 9, 2015 at 4:38

3 Answers 3

3

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(); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes this would make it recursive, Which is terribly insane if the program has to restart from within a for loop.
3

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

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.