2016-03-04 84 views
2

我正在使用Visual Studio 2015,进入项目文件夹> bin> debug> ConsoleApplication1并打开它,命令提示符打开并说:键入一个数字,任意数字!如果我按任何键命令提示立即关闭,尝试删除和编码再次但没有用,仍然关闭,但在Visual Studio中,当我按Ctrl + F5一切正常。CMD在我输入密钥后关闭

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.WriteLine("Type a number, any number!"); 
     ConsoleKeyInfo keyinfo = Console.ReadKey(); 

     PrintCalculation10times(); 

     if (char.IsLetter(keyinfo.KeyChar)) 
     { 
      Console.WriteLine("That is not a number, try again!"); 
     } 

     else 
     { 
      Console.WriteLine("Did you type {0}", keyinfo.KeyChar.ToString()); 
     } 

    } 

    static void PrintCalculation() 
    { 
     Console.WriteLine("Calculating"); 
    } 

    static void PrintCalculation10times() 
    { 
     for (int counter = 0; counter <= 10; counter++) 
     { 
      PrintCalculation(); 
     } 
    } 

} 
+0

这是因为在输入任何内容后,它会写入一行,然后没有其他任何操作会关闭。在main的结尾处请求另一个键,它将等待您在结束之前输入内容。 – Jacobr365

回答

1

这应该可以解决这个问题看,我加入到代码中的注释明白。

static void Main(string[] args) 
{ 
    Console.WriteLine("Type a number, any number!"); 
    ConsoleKeyInfo keyinfo = Console.ReadKey(); 

    PrintCalculation10times(); 

    if (char.IsLetter(keyinfo.KeyChar)) 
    { 
     Console.WriteLine("That is not a number, try again!"); 
    } 

    else 
    { 
     Console.WriteLine("Did you type {0}",keyinfo.KeyChar.ToString()); 
    } 

    //Without the something to do (as you had it) after you enter anything it writes a 
    //line and then has nothing else to do so it closes. Have it do something like this below to fix thisd. 
    Console.ReadLine(); //Now it won't close till you enter something. 

} 

编辑 - 通过请求添加此。在我看到他回应之前,@ManoDestra给出了答案。

您的循环将运行11次(for(int counter = 0; counter < = 10; counter ++))。从0到10。让它< 10或1开始 - ManoDestra

static void PrintCalculation10times() 
{ 
    for (int counter = 0; counter < 10; counter++) //Changed with 
    { 
     PrintCalculation(); 
    } 
} 
+0

好的,非常感谢,你能告诉我为什么它键入“Canculating”11次而不是10次 – IronAmstaff

+2

你的循环将运行11次(for(int counter = 0; counter <= 10; counter ++))。从0到10。使它<10或从1开始。 – ManoDestra

+0

@ManoDestra我用你说的回答他的问题,因为我没有更好的方式来表达它。我希望没关系。 – Jacobr365

2

在控制台应用程序,我通常会添加一些东西沿着这些路线到main()方法的末尾,以防止在关闭程序之前,我可以读我的输出。或实现它,你可以从任何控制台应用程序调用一个单独的实用方法...

while (Console.ReadKey(true).Key != ConsoleKey.Escape) 
{ 
} 

您可以在此之后将任何其他退出代码,如果你想。

或者你可以像这样处理Ctrl-C:How do I trap ctrl-c in a C# console app然后处理它。