0

I am trying to complete a question and I keep running into this error above. Can someone please check my code to make sure I am doing it correctly and also try to fix this error. It's due at 12.

Write a program that reads the contents of a text file. The program should create a dictionary in which the keys are the individual words found in the file and the values are the number of times each word appears. For example, if the word “the” appears 128 times, the dictionary would contain an element with “the” as the key and 128 as the value. The program should either display the frequency of each word or create a second file containing a list of each word and its frequency.

 class Program
    {
        private static string fileName = "sample.txt";

        private static Dictionary<string, int> wordcount;


        private static void ReadFile()
        {
            string fileName = "sample.txt";
            StreamReader input = File.OpenText(fileName);
            char[] separ = { ',', '.', ';' };

            while (!input.EndOfStream) 
            {
                Console.WriteLine("yeet");
                string line = input.ReadLine();
                string[] words = line.Split(separ);
                
                for (int i = 0; i < words.Length; i++)
                {
                    string wordlist = words[i];

                    if (wordcount.ContainsKey(wordlist))
                    {
                        int count;
                        wordcount.TryGetValue(wordlist, out count);
                        wordcount[wordlist] = count + 1;
                    }
                    else
                    {
                        wordcount.Add(wordlist, 1);
                    }
                }
            }
        }

        private static void WriteFile()
        {
            StreamWriter outputFile = new StreamWriter("output.txt");

            foreach(KeyValuePair<string,int> wordCount in wordcount)
            {
                string str = wordCount.Key + ":" + wordCount.Value.ToString();
                outputFile.WriteLine(str);
            }
            outputFile.Close();
        }

0 Answers0