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

Aks*_*lik 0 c# loops

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

 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] + '*';

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

StarGenerator()循环创建错误.

Jon*_*eet 5

这一行:

public static string [] starGenerated = new string[numberOfForbiddenWords];
Run Code Online (Sandbox Code Playgroud)

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

numberOfForbiddenWords = int.Parse(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)

所以,当你打电话StarGenerator,除非numberOfForbiddenWords 0,你要试图访问无效索引.

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