【发布时间】:2017-12-13 02:23:14
【问题描述】:
我正在尝试完成此程序,但一直遇到问题,我无法弄清楚如何获得结果排名的计数我的输出一直为 1,我正在尝试完成此程序我会尽快。输出应该是这样的:
输入数据文件的目录路径:C:\Intel
进入年份:2010
输入性别(M/F):M
输入姓名:哈维尔
哈维尔在 2010 年排名第 190 位
namespace QuestionTwo
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
Console.Write("Enter the directory path of the data files: ");
string filename = Console.ReadLine();
filename.Replace(@"\", @"\\");
Console.Write("Enter the year: ");
string year = Console.ReadLine();
Console.Write("Enter the gender (M/F): ");
string gender = Console.ReadLine();
Console.Write("Enter the name: ");
string name = Console.ReadLine();
filename += "\\yob" + year + ".txt";
string line = "";
try
{
using (StreamReader fin = new StreamReader(filename))
{
while((line = fin.ReadLine()) != null)
{
string[] parsed = line.Split(',');
if (parsed[1] == gender)
{
names.Add(parsed[0]);
}
}
}
for (int i = 0; i < names.Count; i++)
{
if (names[i] == (name))
{
Console.WriteLine(name + " is ranked #" + i + " in year " + year);
}
else //if (names[i] != (name)) // it is a logic error somewhere here
{
Console.WriteLine("The name " + name
+ " is not ranked in year " + year);
}
}
}
catch(Exception e )
{
Console.WriteLine("The file at {0} could not be read."+ e, filename);
}
for(int c = 0; c < names.Count; c++)
{
Console.WriteLine((c + 1) + ". " + names[c]);
}
Console.ReadKey();
}
}
}
【问题讨论】:
-
尝试调试代码以确保值符合您的预期。
-
我做到了,它一直保持在一个
-
你从文件中得到了真正的价值吗?
-
在这部分
for (int i = 0; i < names.Count; i++)中,名称是否包含您需要的确切内容? -
尝试从您的 .text 文件中添加真实的示例数据。
标签: c# console readline ranking