【问题标题】:Having trouble with my code on searching for an element of an array in C#我的代码在 C# 中搜索数组元素时遇到问题
【发布时间】:2016-09-18 21:48:27
【问题描述】:

我一直在为这段代码苦苦挣扎,我似乎无法找出哪里出错了。基本上我想使用整数搜索一个数组,如果它匹配该数组中的一个元素,它会返回一个布尔变量为真。这是不言自明的,但我一生都无法弄清楚!有什么想法吗?

这里是代码;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ArrayProject
{
    class ArrayProgram
    {
        public bool ElementAt(int[] intArray, int valueToBeFound)
        {
            bool intAt = false;
            int numberTofind;

            Console.WriteLine("Please enter the number you wish to search for within the array: ");
            numberTofind = Convert.ToInt32(Console.ReadLine());


            foreach (int x in intArray)
            {
                if (x == numberTofind)
                {
                    intAt = true;
                }
                else
                {
                    intAt = false;
                }
            }
            if (intAt == true)
            {
                Console.WriteLine("{0} is in the array!", numberTofind);
            }
            else
            {
                Console.WriteLine("{0} is not in the array.", numberTofind);
            }

            return intAt;
        }
        public void RunProgram()
        {
            int[] intArray = { 20, 30, 40, 50, 60, 50, 40, 30, 20, 10 };
            int numberTofind = 0;

            ElementAt(intArray, numberTofind);

        }  // end RunProgram()

        static void Main(string[] args)
        {
            ArrayProgram myArrayProgram = new ArrayProgram();
            myArrayProgram.RunProgram();

            Console.WriteLine("\n\n===============================");
            Console.WriteLine("ArrayProgram: Press any key to finish");
            Console.ReadKey();
        }
    }
}

【问题讨论】:

  • 您的代码返回什么?你期望发生什么?如果你找到你的号码,我可能会建议退出循环......
  • 威廉的建议是正确的。我认为您没有得到正确的返回值,因为 foreach 循环正在继续,而不是返回或退出循环。还有 Dmitriy 提到的 Contains 和 IndexOf,它们将为您执行此计算。
  • 使用 List 而不是数组。 List 有更多功能: List intArray = new List() { 20, 30, 40, 50, 60, 50, 40, 30, 20, 10 }; int index = intArray.IndexOf(60);
  • 我是编程新手,我没有意识到 foreach 循环会是无限的?我以为它只循环一次。仍然有很多东西要学,哈哈。编辑:感谢您的回复!我没有使用任何这些方法或列表的原因是因为给我们示例的人告诉我们,没有它们我们也可以做到。

标签: c# arrays visual-studio find element


【解决方案1】:
        int[] intArray = { 20, 30, 40, 50, 60, 50, 40, 30, 20, 10 };
        int numberToFind = 0;

        //variant 1 (using System.Linq):
        bool bInside1 = intArray.Contains(numberToFind);

        //variant2
        bool bInside2 = Array.IndexOf(intArray, numberToFind) >= 0;

如果你想编写自己的函数:

    bool IsInside(int[] arrToSearch, int nToSearch)
    {
        foreach (int n in arrToSearch)
        {
            if (n == nToSearch)
                return true;
        }
        return false; //not found
    }

【讨论】:

  • 谢谢!现在就试一试。
【解决方案2】:

问题是您的循环会继续检查元素并更新intAt,即使它找到了您要查找的元素。

如果数组是{1, 2, 3, 4},并且您的代码正在搜索1,它将首先检查索引0。这是一个匹配,所以intAt 变成了true。接下来它将尝试索引1。这个不匹配,所以它将intAt 设置为假。然后它将尝试索引23 等,但永远找不到匹配项。

【讨论】:

  • 哦!这实际上很有意义,所以我可以添加一个休息时间;如果找到元素,则发送给代码?
【解决方案3】:

您可以使用 Linq 轻松做到这一点。

using System.Linq;

public static string test(int[] numberArray, int find) 
{ 
            bool s = false;
            numberArray.ToList().ForEach(x => { if (x == find) s = true; }); 
            return s ? "It contains it." : "Can't find it.";
}

但是有一种方法可以做到这一点。正如我上面所说的那样,您可以将 .Contains 与数组一起使用。

【讨论】:

  • > numberArray.ToList().ForEach(x => { if (x == find) s = true; });写的方式,就像编程的简写吗?我所学的只是长手版本。
  • 它是一种 linq 方法。基本上是一种压缩语法。虽然它与 foreach 循环相同。没有性能提升。
【解决方案4】:

如果你想保留你的实现,试试这个:

class ArrayProgram
{
    public bool ElementAt(int[] intArray, int valueToBeFound)
    {
        foreach (int x in intArray)     
            if (x == valueToBeFound)        // if you found your value in the array
                return true;                // you return true

        return false;   // otherwise, by this point the foreach has looped through all the elements and hasn't once entered in the above if (so it hasn't found your value) = you return false
    }

    public void RunProgram()
    {
        int[] intArray = { 20, 30, 40, 50, 60, 50, 40, 30, 20, 10,99 };
        int numberTofind;

        // I noticed that you're not using the numberTofind value either, so:

        Console.Write("Please enter the number you wish to search for within the array: ");
        numberTofind = Convert.ToInt32(Console.ReadLine());

        // and since you made a function that returns true if your value has been found, you might as well use it like this

        if(ElementAt(intArray, numberTofind)) // if the function returns true
            Console.WriteLine("{0} is in the array!", numberTofind);
        else
            Console.WriteLine("{0} is not in the array.", numberTofind);
    }  // end RunProgram()

    static void Main(string[] args)
    {
        ArrayProgram myArrayProgram = new ArrayProgram();
        myArrayProgram.RunProgram();

        Console.WriteLine("\n\n===============================");
        Console.WriteLine("ArrayProgram: Press any key to finish");
        Console.ReadKey();
    }
}

【讨论】:

  • 谢谢!这使它更加清晰,因为我可以使用我现有的代码。我可以看到我哪里出错了:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
相关资源
最近更新 更多