C#检查数组中是否存在数字

时间:2012-12-31 23:52:03

标签: c#

我试图让用户输入10个数字并将它们存储到数组中。然后提示用户输入任何数字以检查数字是否已存储在数组中。当我输入任何数字时屏幕将消失,如果数字已存在,我无法验证。请看我的代码。提前致谢。

static void Main(string[] args)
    {
        int[] numCheck = new int[10];
        int[] userInput = new int[1];

        Console.WriteLine("Please enter 10 numbers: ");

        for (int i = 0; i < 10; i++)
        {
            Console.Write("Number {0}: ", i + 1);
            numCheck[i] = int.Parse(Console.ReadLine());
        }

        Console.WriteLine("Please enter any number to check if the number already exist");

        for (int j = 0; j <= 10; j++)
        {
            if (userInput == numCheck)
            {
                Console.Write("The number {0} is in the index", numCheck);
                userInput[j] = int.Parse(Console.ReadLine());
            }

            else 
            {
                Console.Write("The number {} is not in the index", numCheck);
            }
        }

3 个答案:

答案 0 :(得分:2)

您只需从用户处获取1个项目,因此无需声明数组

int userInput;

//read userInput

if (numCheck.Any(i => i == userInput))
{
    Console.Write("The number {0} is in the index", userInput);
}
else
{
    Console.Write("The number {} is not in the index", userInput);
}

答案 1 :(得分:1)

不应该这样:

if (userInput == numCheck)

是:

if (userInput[0] == numCheck[j])

答案 2 :(得分:1)

建议的替代方案:

static void Main(string[] args)
{
    int[] numCheck = new int[10];
    Console.WriteLine("Please enter 10 numbers: ");

    for (int i = 0; i < 10; i++)
    {
        Console.Write("Number {0}: ", i + 1);
        numCheck[i] = int.Parse(Console.ReadLine());
    }

    Console.WriteLine("Please enter any number to check if the number already exist");
    int userInput = int.Parse(Console.ReadLine());

    for (int i = 0; i < 10; i++)
    {
        if (userInput == numCheck[i])
        {
            Console.Write("FOUND NUMBER");

            break;
        }
    }
 }