有没有一种方法可以通过为用户提供输入要退出的数字的选项来退出while while循环?

时间:2019-02-05 00:01:39

标签: c#

我创建了一个数组,该数组可让企业输入它们提供的邮政编码,并使其具有搜索能力。我想为用户提供输入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();

输入它们提供的邮政编码,并使其具有搜索能力。 显示输入到数组中的邮政编码,然后提供搜索或退出程序的选项。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

通常,每当在以{}为界的代码块中声明变量(例如ifwhile)时,该变量将仅存在于该块内部。为了回答您的问题,您的lookup变量仅存在于while循环内,因此不能在条件中使用。为了防止这种情况,请在循环之外定义它。

Int64 lookup = 1;
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 ");

    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);