我是 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);
}
}
最佳答案
return
语句停止当前方法的执行并将控制权返回给调用者。在您的情况下,您的 linesinfile
方法中似乎有过早的 return count;
语句。尝试将 return count;
移动到 linesinfile
方法的end,就在结束 }
之前,它应该可以。
关于c# - 无法访问的代码和验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8870397/