如何通过比较用户输入的搜索int数组VS字符串数组

时间:2019-02-01 22:17:20

标签: c#

如何检查用户输入是否与数组中的数字匹配?

我已经学会了使用字符串数组来比较用户输入或搜索,但是对int数组进行相同的操作对我来说不起作用。

zipCode[i] = 0;
int userZip = 0;

do 
{
    Console.WriteLine( "enter a 5 digit zip code to see if it is supported in our area." );
    Console.WriteLine( );
    Console.WriteLine( "Enter a 0 to exit the program" );
    userZip = 0;
    if ( userZip == zipCode[i] ) 
    {
        found = true;
        if ( found ) 
        {
            Console.WriteLine( "We support zip code {0}", userZip ); ;
        } 
        else 
        {
            Console.WriteLine( "We do not support", userZip );
        }
    }
} while ( userZip != 0 );

Console.ReadLine( );

5 个答案:

答案 0 :(得分:1)

  

如何检查用户输入是否匹配数组中的数字?

//--------------------
// my_module.h
//--------------------

// my_module configuration struct
typedef struct my_module_config_s
{
    int my_config_param_int;
    int my_config_param_float;
} my_module_config_t;

void my_module_open(my_module_h * my_module_h_p, const my_module_config_t *config);

//--------------------
// my_module.c
//--------------------

void my_module_open(my_module_h * my_module_h_p, const my_module_config_t *config)
{
    // Ensure the passed-in pointer is not NULL (since it is a core dump/segmentation fault to try to dereference 
    // a NULL pointer)
    if (!my_module_h_p)
    {
        // Print some error or store some error code here, and return it at the end of the function instead of 
        // returning void.
        goto done;
    }

    // Now allocate the actual memory for a new my_module C object from the heap, thereby dynamically creating this
    // C-style "object".
    my_module_h my_module; // Create a local object handle (pointer to a struct)
    my_module = malloc(sizeof(*my_module)); // Dynamically allocate memory for the full contents of the struct "object"
    if (!my_module) 
    {
        // Malloc failed due to out-of-memory. Print some error or store some error code here, and return it
        // at the end of the function instead of returning void.
        goto done;
    }

    // Initialize all memory to zero (OR just use `calloc()` instead of `malloc()` above!)
    memset(my_module, 0, sizeof(*my_module));

    // Now initialize the object with values per the config struct passed in.
    my_module->my_private_int1 = config->my_config_param_int;
    my_module->my_private_int2 = config->my_config_param_int*3/2;
    my_module->my_private_float = config->my_config_param_float;        
    // etc etc

    // Now pass out this object to the user, and exit.
    *my_module_h_p = my_module;

done:
}

答案 1 :(得分:0)

这是int阵列为Enumerable<int>,因此你可以只使用Containshttps://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.contains?view=netframework-4.7.2

答案 2 :(得分:0)

  

如何检查用户输入是否与数组中的数字匹配?

我将回答这个问题,尽管由于示例代码不完整,并且无法确切说明其功能,所以我无法使用您的示例代码发布示例。

首先,让我们创建一个从用户那里获取整数的方法。该方法将不断循环直到用户输入有效的整数:

public static int GetIntFromUser(string prompt = null)
{
    int input;
    int row = Console.CursorTop;
    int promptLength = prompt?.Length ?? 0;

    do
    {
        Console.SetCursorPosition(0, row);
        Console.Write(prompt + new string(' ', Console.WindowWidth - promptLength - 1));
        Console.CursorLeft = promptLength;
    } while (!int.TryParse(Console.ReadLine(), out input));

    return input;
}

现在,我们可以使用该方法从用户获取邮政编码:

int userZipCode = GetIntFromUser("Enter a 5 digit zip code to see if it's supported: ");

现在,我假设您有一组受支持的邮政编码。也许像这样:

private static int[] GetSeattleZipCodes()
{
    return new []
    {
        98101, 98102, 98103, 98104, 98105, 98106, 98107, 98108, 98109, 98110,
        98111, 98112, 98113, 98114, 98115, 98116, 98117, 98118, 98119, 98121,
        98122, 98124, 98125, 98126, 98127, 98129, 98131, 98133, 98134, 98136,
        98138, 98139, 98141, 98144, 98145, 98146, 98148, 98154, 98155, 98158,
        98160, 98161, 98164, 98165, 98166, 98168, 98170, 98174, 98175, 98177,
        98178, 98181, 98185, 98188, 98190, 98191, 98194, 98195, 98198, 98199
    };
}

因此,现在我们有一个int用户输入和一个int[]有效邮政编码,因此要查看有效邮政编码数组是否包含用户邮政编码,我们可以使用Contains方法:

int[] seattleZipCodes = GetSeattleZipCodes();
bool found = seattleZipCodes.Contains(userZipCode);

答案 3 :(得分:0)

TheFastCat击败了我,但是:

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        private static IEnumerable<string> zipCodes = new string[] { "90210", "94102", "98101", "80014" };

        static void Main(string[] args)
        {

            Console.WriteLine("enter a 5 digit zip code to see if it is supported in our area, or '0' to exit");
            do {
                // Read next line
                string userZip = Console.ReadLine().Trim();

                // Exit program?
                if (userZip == "0")
                    break;

                // Validate input
                if (userZip.Length != 5)
                {
                    Console.WriteLine("ERROR: Zip code {0} is {1} characters; expected 5", userZip, userZip.Length);
                    continue;
                }
                int n;
                bool isNumeric = int.TryParse(userZip, out n);
                if (!isNumeric)
                {
                    Console.WriteLine("ERROR: Zip code {0} must be numeric", userZip);
                    continue;
                }

                // Finally, see if our zip code matches a zip code in the list
                bool found = zipCodes.Contains(userZip);
                if (found)
                {
                    Console.WriteLine("We support zip code {0}", userZip); ;
                }
                else
                {
                    Console.WriteLine("We do not support " + userZip);
                }
            } while (true);
            Console.WriteLine("Done: exiting program");
        } 
    }
}

注意:

  1. 初始化列表

  2. 验证输入

  3. 使用IEnumerable.Contains() ... 必然与LINQ搞乱。

  4. 使用“ break”和“ continue”来控制循环,无需必然需要一个无关的变量。

答案 4 :(得分:-1)

TheFastCat和鲁弗斯大号做了伟大的工作。 我只想添加一个例子。使用“无功”的数据类型使事情变得简单,耐用,以及在C# 此示例在两种情况下都使用var数据类型演示了“ int”和“ string”。哈伯金,祝你好运。

static void Main(string[] args)
{
        //var ZipCodes = new List<string>() { "04846", "40569", "76859","54896", "84623" }; // ZipCodes are stored as a string in a List
        var ZipCodes = new List<int>() { 04846, 40569, 76859, 54896, 84623 }; // ZipCodes are stored as an int in a List

        //var userZip = "";
        var userZip = 0;

        do
        {
            Console.WriteLine("Enter a 5 digit zip code to see if it is supported in our area.");

            //userZip = Console.ReadLine(); // Enable to receive userZip as a string
            userZip = int.Parse(Console.ReadLine()); // receive userZip as an int

            if (ZipCodes.Contains(userZip))
            {
                Console.WriteLine("We support zip code {0}", userZip);
            }
            else
            {
                Console.WriteLine("We do not support", userZip);
            }

            //} while (userZip != "0");
        } while (userZip != 0);
    }