【发布时间】:2015-03-31 01:48:15
【问题描述】:
我正在为我的计算机科学课做作业。城市人口普查数据位于保存其公民记录的文本文件中。每行将有四个不同数据类型的字段(年龄、性别、婚姻状况和地区),用逗号分隔。比如22、F、M、1。
我应该如何处理这个问题?我的想法是我应该使用两个一维数组,一个用于年龄,一个用于地区。我需要以后能够计算每个区有多少人,以及整个城市有多少不同年龄组的人。
如何读取每一行并将我想要的信息放入每个数组中?
编辑** 这就是我到目前为止所做的。我正在尝试将我的数据从字段中分离到四个不同的数组中。这就是我卡住的地方。
FileStream fStream = new FileStream("test.txt", FileMode.Open, FileAccess.Read);
StreamReader inFile = new StreamReader(fStream);
string inputRecord = "";
string[] fields;
int[] ageData = new int[1000];
string[] genderData = new string[1000];
string[] maritalData = new string[1000];
int[] districtData = new int[1000];
inputRecord = inFile.ReadLine();
while (inputRecord != null)
{
fields = inputRecord.Split(',');
int i = 0;
ageData[i] = int.Parse(fields[0]);
genderData[i] = fields[1];
maritalData[i] = fields[2];
districtData[i] = int.Parse(fields[3]);
i++;
inputRecord = inFile.ReadLine();
}
编辑 2**
第一个问题,我决定使用下面的代码来找出人口普查数据的每个地区有多少公民。
for (int x = 1; x <= 22; x++)
for (int y = 0; y < districtData.Length; y++)
if (districtData[y] == x)
countDist[x]++;
for (int x = 1; x <= 22; x++)
Console.WriteLine("District " + x + " has " + countDist[x] + " citizens");
在我的.Writeline 中,当x 达到两位数时,它会脱离我的列。我怎样才能更好地排列我的列?
第二个问题,我不太清楚如何使用 if 语句将 ageData 中的值分成年龄组。
【问题讨论】:
-
感谢您将我的原始帖子从一段文本编辑成更易于阅读的内容。