2015-08-09 158 views
1

我创建了一个小型应用程序,做一个小的转换。在节目的最后,我已经创建了一个方法,它允许用户进行另一次计算,如果他们按“R”。所有我想做的事情是,如果他们按R键,带他们回到主的开始,否则终止程序。我不想使用goto。这是我到目前为止,以及我得到的错误。C#重新启动控制台应用程序

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

+0

尝试使用'while'。 – Athari

+0

请将代码作为文本发布(格式正确) - 链接到随机网站上的图像并不真正欢迎SO,另外它可以消失并且使得该帖子对于未来的读者完全无用。 –

+0

已注意。不会再这样做,谢谢。 – Godzilla2456

回答

0

我建议你使用其他功能,而不是主要的()。请参考下面的代码:

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(); 
    } 
+0

递归的解决方案? –

+0

是的,这会使它递归,如果程序必须从for循环中重新启动,这是非常疯狂的。 –

0

在你的情况,你想重复的东西,所以当然你应该使用一个while循环。使用while循环来包装所有的代码像这样:

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

然后你提示用户在循环的结束,进入“R”:

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

如果用户输入[R那么循环继续完成这项工作。 break意味着停止在循环执行的东西。

2

While循环将非常适合,但既然你说程序应该运行,然后给了用户再次运行的选项,更好的循环将是Do While。 while和Do While之间的区别在于Do While将始终运行至少一次。

 string inputStr; 

     do 
     { 
      RunProgram(); 

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

     TerminateProgram();