Недоступный код и подтверждение - PullRequest
1 голос
/ 15 января 2012

Я (очень) новичок в 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 ]

3 голосов
/ 15 января 2012

этот код

return count;       //displays the line count

выполняется безоговорочно, что, в свою очередь, означает, что он завершает выполнение метода ... это приводит к недоступности остальной части кода в этом методе.

3 голосов
/ 15 января 2012
Оператор

A return останавливает выполнение текущего метода и возвращает управление вызывающей стороне. В вашем случае у вас, похоже, есть преждевременный оператор return count; в вашем методе linesinfile. Попробуйте переместить return count; в end метода linesinfile непосредственно перед закрытием }, и оно должно работать.

2 голосов
/ 15 января 2012
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, поэтому остальная часть кода в этой функции обычно недоступна.

1 голос
/ 15 января 2012

Ваш код содержит много избыточности. Я попытался обрезать его и отобразить 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);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...