首页 > 解决方案 > 有没有办法通过让用户选择输入数字退出来退出这个 do while 循环?

问题描述

我创建了一个数组,允许企业输入他们服务的邮政编码,并赋予他们搜索的能力。我想让用户能够输入 0 以退出程序。如何在 do while 循环的“while”部分执行此操作?(我知道以字符串形式输入邮政编码更好)。

我试过把while(lookup != 0),我得到一个错误,告诉我名称查找不存在。

int[] zipCodes = new int[5];



        for (int i = 0; i < zipCodes.Length; i = i + 1)
        {
            Console.WriteLine("Enter a 5 digit zip code that is supported in your area");
            zipCodes[i] = Convert.ToInt32(Console.ReadLine());
        }

        Array.Sort(zipCodes);
        for (int i = 0; i < zipCodes.Length; i = i + 1)
        {
            Console.WriteLine("zip codes {0}: {1}", i, zipCodes[i]);
        }


        do
        {
            Console.Write("Enter a zip code to look for: ");
            Console.WriteLine();
            Console.WriteLine("You may also enter 0 at any time to exit the program ");

            Int64 lookup = Convert.ToInt64(Console.ReadLine());
            int success = -1;


            for (int j = 0; j < zipCodes.Length; j++)
            {
                if (lookup == zipCodes[j])
                {
                    success = j;
                }
            }
            if (success == -1) // our loop changes the  -1 if found in the directory
            {
                Console.WriteLine("No, that number is not in the directory.");
            }

            else
            {
                Console.WriteLine("Yes, that number is at location {0}.", success);
            }
        } while (lookup != 0);

        Console.ReadLine();

输入他们提供的邮政编码,并赋予他们搜索的能力。显示输入到数组中的邮政编码,然后选择搜索或退出程序。

标签: c#

解决方案


就像我在上面的评论中所说:您需要在 do while 循环之外定义查找变量,它当前仅存在于其中,因此当条件运行时会导致错误:)

Int64 lookup = 1; //or something other than 0
do
{
   ...
    your code
   ...
} while (lookup != 0);

推荐阅读