如何使控制台应用程序运行,直到用户输入"Q","q","Quit"为止.或“退出"终止吗? [英] How do I make an console application run until the user enters "Q", "q", "Quit" or "quit" to terminate it?

查看:272
本文介绍了如何使控制台应用程序运行,直到用户输入"Q","q","Quit"为止.或“退出"终止吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在用户输入"Q","q","Quit"或"quit"以终止它之前运行控制台应用程序?

How do I make an console application run until the user enters "Q", "q", "Quit" or "quit" to terminate it?

这是我当前的代码:

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

推荐答案

假设您的程序中没有其他错误,只需添加几行这样的内容:

Assuming there aren't any other bugs in your program... just add a couple lines like this:

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
}

这篇关于如何使控制台应用程序运行,直到用户输入"Q","q","Quit"为止.或“退出"终止吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆