我做的while循环运行次数超过它应该(我认为)

时间:2015-03-16 00:43:56

标签: c# database loops do-while

这是一个数据库程序,通过输入数字0-7,您可以对数据文件执行不同的操作。每当我尝试通过输入0来退出时,它会再次通过循环发送给我,然后一旦我输入另一个0它就会退出。

static void Main(string[] args)
        {

            do
            {
                DoAQuery();
                Console.WriteLine();


            } while (DoAQuery() != "0");

        }

        static string DoAQuery()
        {
            string prompts = "0: Quit \n" +
                             "1: Who wrote <song name> \n" +
                             "2: What does <musician name> play \n" +
                             "3: What songs were written by <composer> \n" +
                             "4: Who plays in the <band name> \n" +
                             "5: Who's recorded <song name> \n" +
                             "6: What songs has the <band name> recorded \n" +
                             "7: Has the <band name> recorded <song name> \n";

            Console.WriteLine(prompts);

            Console.Write("Enter a command number: ");
            string cmd = Console.ReadLine();


            switch (cmd)
            {
                case "0" :
                    return cmd;

                case "1" :
                    Case1();
                    return cmd;

                case "2" :
                    Case2();
                    return cmd;

                case "3":
                    Case3();
                    return cmd;

                case "4":
                    Case4();
                    return cmd;

                case "5":
                    Case5();
                    return cmd;

                case "6":
                    Case6();
                    return cmd;

                case "7":
                    Case7();
                    return cmd;

                default:
                    Console.WriteLine("!!Command must be a number 0-7!!");
                    return "1";
            }

这是打印的内容

    loaded 8 tunes
    0: Quit
    1: Who wrote <song name>
    2: What does <musician name> play
    3: What songs were written by <composer>
    4: Who plays in the <band name>
    5: Who's recorded <song name>
    6: What songs has the <band name> recorded
    7: Has the <band name> recorded <song name>

    Enter a command number: 0

    0: Quit
    1: Who wrote <song name>
    2: What does <musician name> play
    3: What songs were written by <composer>
    4: Who plays in the <band name>
    5: Who's recorded <song name>
    6: What songs has the <band name> recorded
    7: Has the <band name> recorded <song name>
    Enter a command number: 0

基本上我只想输入零来立即退出程序。提前谢谢!!

1 个答案:

答案 0 :(得分:4)

这种情况正在发生,因为您在代码中两次调用DoAQuery()

你可以用这种方式重构它:

string response;
do
{
    response = DoAQuery();
    Console.WriteLine();
} while (response != "0");

因此,您可以捕获用户选择一次,然后多次使用它。

相关问题