Index out of Range exception in arrays

I am continuously getting out of range exception in my code. I went into the debug mode and found that it was giving an error for the zeroth index itself. Any help would be greatly appreciated.

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

        }

    }
}

The StarGenerator() loops create the error.

Jon Skeet
people
quotationmark

This line:

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

... is executed when the class is initialized. That will happen while numberOfForbiddenWords is still 0, i.e. long before this line is executed:

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

So when you call StarGenerator, unless numberOfForbiddenWords is still 0, you're going to be trying to access invalid indexes.

I would try to avoid all these static variables - I suspect they're confusing you in terms of when initialization is occurring.

people

See more on this question at Stackoverflow