在用户输入“Q”,“q”,“退出”或“退出”以终止它之前,如何运行控制台应用程序?

时间:2010-09-17 04:31:16

标签: c# console-application exit

如果用户输入“Q”,“q”,“退出”或“退出”以终止它,我该如何运行控制台应用程序?

这是我目前的代码:

public class Class1
{
  [STAThread]
  static void Main(string[] args)
  {
    string userName;
    int i = 0, totalCal = 0, cal = 1;

    Console.WriteLine("Welcome to the magical calorie counter!");
    Console.WriteLine();
    Console.Write("Enter in your name -> ");
    userName = Console.ReadLine();

    for (i = 0; i <= 10; i++)
    {
      Console.WriteLine("Hello {0}.....Let's add some calories!!", userName);
    }// end for loop

    Console.WriteLine();

    while (cal != 0)
    {
      Console.Write("Enter some Calories:<or 0 to quit>: ");

      cal = Convert.ToInt32(Console.ReadLine());

      Console.WriteLine("You entered {0}", cal);
      Console.WriteLine();

      totalCal += cal;
      Console.WriteLine();
      Console.WriteLine("-------------------So far you have a total of {0}------------------", totalCal);
      Console.WriteLine();    
      Console.WriteLine();
    }// end of while 
  }// end of amin
}//end of class

3 个答案:

答案 0 :(得分:5)

假设您的程序中没有任何其他错误...只需添加如下几行:

using System;

class Class1
{

    [STAThread]
    static void Main(string[] args)
    {
        string userName;
        string line;
        int i = 0, totalCal = 0, cal = 1;

        Console.WriteLine("Welcome to the magical calorie counter!");
        Console.WriteLine();
        Console.Write("Enter in your name -> ");
        userName = Console.ReadLine();

        for (i = 0; i <= 10; i++)
        {
            Console.WriteLine("Hello {0}.....Let's add some calories!!", userName);
        }// end for loop
        Console.WriteLine();


        while (true)
        {

            Console.Write("Enter some Calories:<or 0 to quit>: ");
            line = Console.ReadLine().ToLower();
            if (line == "q" || line == "quit")
            {
                break;
            }
            else if (!int.TryParse(line, cal))
            {
                Console.WriteLine("Not a valid option. Please try again.");
                continue;
            }
            Console.WriteLine("You entered {0}", cal);
            Console.WriteLine();

            totalCal += cal;
            Console.WriteLine();
            Console.WriteLine("-------------------So far you have a total of {0}------------------", totalCal);
            Console.WriteLine();
            Console.WriteLine();
        }// end of while 
    }// end of amin
}

答案 1 :(得分:0)

我认为退出,或退出是好的。或者你可以接受e或q。

答案 2 :(得分:-1)

我更喜欢精通键盘用户可能已知的键盘快捷键,例如Ctrl + W,这是在现代网络浏览器上关闭标签的默认键。