我想找出用连字符分隔的连续和非连续数字。一旦我运行这个给定的代码,它就会给我一个错误,因为"System.ArgumentOutOfRangeException:‘索引超出了范围。必须是非负数并且小于集合的大小。参数名:索引’“。这段代码有什么问题,如果有人知道的话请解释一下。
    public static void Main(string[] args)
    {
        Console.Write("Enter a few numbers (eg 1-2-3-4): ");
        var input = Console.ReadLine();
        var numArray = new List<int>();
        foreach (var number in input.Split('-'))
        {
            numArray.Add(Convert.ToInt32(number));
        }
        numArray.Sort();
        var isConsecutive = true;
        for (int i = 0; i < numArray.Count; i++)
        {
            if (numArray[i] != numArray[i + 1] - 1)
            {
                isConsecutive = false;
                break;
            }
        }
        if (isConsecutive)
        {
            Console.WriteLine("Consecutive");
            Console.ReadLine();
        }
        else
        {
            Console.WriteLine("Not Consecutive");
            Console.ReadLine();
        }
    }发布于 2020-06-03 16:31:32
问题是:
numArray[i + 1]当您的i到达最后一个索引时,在i+1中没有任何项目以超出范围的索引结束。
如果你真的需要i + 1和安全保护,你需要重新考虑逻辑,这样你就不会访问实际上不存在的索引。
你可能想要:
for (int i = 0; i < numArray.Count - 1; i++)这样它就会在数组的倒数第二项停止。
https://stackoverflow.com/questions/62168358
复制相似问题