无法访问的代码和验证

时间:2012-01-15 14:27:08

标签: c# dictionary

我(非常)是C#的新手,并试图从.txt文件中获取一个字符串列表,并创建我想要显示的最常见的20个字符串。这是一个项目,我不会撒谎,但我无法弄清楚为什么我无法达到代码的某一部分,并希望得到任何帮助。

到目前为止我的代码是:

// I have used framework 4  
public class Program
{

    private static int Compare(KeyValuePair<string, int> kv1, KeyValuePair<string, int> kv2)
    {
        return kv2.Value == kv1.Value ? kv1.Key.CompareTo(kv2.Key) : kv2.Value - kv1.Value;
    }

    public static void Main()
    {
        {
            try
            {
                Dictionary<string, int> histogram = new Dictionary<string, int>();      // creates a dictionary from the text file
                using (StreamReader reader = new StreamReader("tweets.txt"))        //reads the text file specified
                {
                    string difline;
                    while ((difline = reader.ReadLine()) != null)       //continues until no lines left
                    {
                        if (histogram.ContainsKey(difline))     //counts specific strings
                            ++histogram[difline];
                        else
                            histogram.Add(difline, 1);
                    }
                }


                using (StreamReader sr = new StreamReader("tweets.txt"))        // Create an instance of StreamReader to read from a file.
                // also closes the StreamReader.
                {
                    string line;
                    long linecount = linesinfile("tweets.txt");
                    Console.WriteLine(linecount);
                    TextWriter tw = new StreamWriter("tweets.html"); //create a writer
                    tw.WriteLine("<html> <body>");
                    while ((line = sr.ReadLine()) != null) // Read and display lines from the file until the end of the file is reached.
                    {
                        Console.WriteLine(line);
                        tw.WriteLine("{0} <br />", line); //write the lines of text to the html file

                    }
                    tw.WriteLine("</html> </body>");
                    tw.Close(); //close the writer
                }

            }

            catch (Exception e)
            {

                Console.WriteLine("The file could not be read:"); // Let the user know what went wrong.
                Console.WriteLine(e.Message);
            }
            Console.Write("\nPress any key to continue . . . ");
            Console.ReadKey(true);
        }
    }


    static long linesinfile(string l)
    {
        long count = 0;
        using (StreamReader r = new StreamReader(l))
        {
            string line;
            while ((line = r.ReadLine()) != null)       //counts lines until last line
            {
                if (line.StartsWith("#") & line.Length > 1)       //only count lines which start with #
                {
                    count++;    //increases the count
                }
            }
            return count;       //displays the line count
        }

        //this code is unreachable

        Dictionary<string, int> histogram = new Dictionary<string, int>();
        using (StreamReader reader = new StreamReader("tweets.txt"))
        {
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                if (histogram.ContainsKey(line))
                    ++histogram[line];
                else
                    histogram.Add(line, 1);
            }
            {
                Console.Write("{0} ", histogram);
            }
        }

        List<KeyValuePair<string, int>> sortedHistogram = new List<KeyValuePair<string, int>>(histogram);
        sortedHistogram.Sort(Compare);
        foreach (KeyValuePair<string, int> kv in sortedHistogram)
            Console.WriteLine("{0}\t{1}", kv.Value, kv.Key);
    }
}

4 个答案:

答案 0 :(得分:3)

return语句停止执行当前方法并将控制权返回给调用者。在您的情况下,您的return count;方法中似乎有一个过早的linesinfile语句。尝试将return count;移动到linesinfile方法的 end ,就在结束}之前,它应该可以正常工作。

答案 1 :(得分:3)

此代码

return count;       //displays the line count

是无条件执行的,这反过来意味着它结束了方法的执行......这导致该方法中的其余代码无法访问。

答案 2 :(得分:2)

static long linesinfile(string l)
        {
            long count = 0;
            using (StreamReader r = new StreamReader(l))
            {
                string line;
                while ((line = r.ReadLine()) != null)       //counts lines until last line
                {
                    if (line.StartsWith("#") & line.Length > 1)       //only count lines which start with #
                    {
                        count++;    //increases the count
                    }
                }
                return count;       //displays the line count
            }

在您的函数中,您执行无条件return count,因此此函数中的其余代码通常无法访问。

答案 3 :(得分:1)

您的代码包含大量冗余。我试图将其修剪下来并将前20个结果显示给控制台(消除HTML文件输出)。

// I have used framework 4  

using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    private static int Compare(KeyValuePair<string, int> kv1, KeyValuePair<string, int> kv2)
    {
        return kv2.Value.CompareTo(kv1.Value);   // descending order
    }

    public static void Main()
    {
        try
        {
            int linecount = 0;
            Dictionary<string, int> histogram = new Dictionary<string, int>();      // creates a dictionary from the text file
            using (StreamReader reader = new StreamReader("tweets.txt"))        //reads the text file specified
            {
                string difline;
                while ((difline = reader.ReadLine()) != null)       //continues until no lines left
                {                   
                    linecount++;    //increases the count

                    if (histogram.ContainsKey(difline))     //counts specific strings
                        ++histogram[difline];
                    else
                        histogram.Add(difline, 1);
                }
            }

            Console.WriteLine("Line count: " + linecount);

            Console.WriteLine("Top 20:");
            List<KeyValuePair<string, int>> sortedHistogram = new List<KeyValuePair<string, int>>(histogram);
            sortedHistogram.Sort(Compare);
            foreach (KeyValuePair<string, int> kv in sortedHistogram.Take(20))
                Console.WriteLine("{0}\t{1}", kv.Value, kv.Key);
        }

        catch (Exception e)
        {

            Console.WriteLine("The file could not be read:"); // Let the user know what went wrong.
            Console.WriteLine(e.Message);
        }

        Console.Write("\nPress any key to continue . . . ");
        Console.ReadKey(true);
    }
}