繁体   English   中英

数组中的索引超出范围异常

[英]Index out of Range exception in arrays

我在代码中不断超出范围异常。 我进入调试模式,发现它为第零个索引本身提供了错误。 任何帮助将不胜感激。

 namespace StringTest7
    {
        class Program
        {
        static void Main(string[] args)
        {

            Input();
            StarGenerator();
            RemovingWords();
            Console.ReadKey();

        }

        public static string [] forbiddenWords = new string [10];
        public static int numberOfForbiddenWords;

        public static string inputValue;

        public static void Input()
        {
            Console.WriteLine("Enter the value.");
            inputValue = Console.ReadLine();
            Console.WriteLine("Enter the number of forbidden words.");
            numberOfForbiddenWords = int.Parse(Console.ReadLine());
            Console.WriteLine("Please enter the forbidden words");
            for (int i = 0; i < numberOfForbiddenWords; i++)
                forbiddenWords[i] = Console.ReadLine();
        }

        public static void RemovingWords()
        {



            for(int i =0;i<numberOfForbiddenWords;i++)
            {
                for(int j = 0; j< inputValue.Length - 1; i++)
                {
                        inputValue.Replace(forbiddenWords[i],
                                starGenerated[i]);
                }
            }

            Console.WriteLine(inputValue);
        }

        public static string [] starGenerated = new string[numberOfForbiddenWords];
        public static void StarGenerator()
        {

            for (int i = 0; i < numberOfForbiddenWords; i++)
                starGenerated[i] = "";

            for (int k = 0; k < numberOfForbiddenWords; k++)
                for (int i = 0; i < forbiddenWords[k].Length-1; i++)
                    starGenerated[k] = starGenerated[k] + '*';

        }

    }
}

StarGenerator()循环会产生错误。

这行:

public static string [] starGenerated = new string[numberOfForbiddenWords];

...在类初始化时执行。 numberOfForbiddenWords仍然为0时,即在执行此行之前很久,就会发生这种情况:

numberOfForbiddenWords = int.Parse(Console.ReadLine());

因此,当您调用StarGenerator ,除非numberOfForbiddenWords 仍然为 0,否则您将尝试访问无效索引。

我会尽量避免使用所有这些静态变量-我怀疑它们会在初始化发生时使您感到困惑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM