【发布时间】: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