1 つの配列を使用して 3 つのデータを追跡する方法について、あなたの助けが必要です。学校の課題であり、そうする必要があるため、1 つの配列を使用する必要があります。配列は、Province ID、Region ID、および各地域の人口を追跡する必要があります。13 の州があり、各州には 48 の地域があります。配列は固定サイズなので、624 x 3 の多次元配列を使用しました。最初の列は州 ID、2 番目は地域 ID、3 番目の列は人口です。各州には 13 の州と 48 の地域があるため、13*48 = 624 であるため、行を 624 に設定します。
データを挿入して、このように表示することができました
ProvinceID # 1 RegionID # 1: 125000
代わりに、州ごとに地域と人口を表示したいと思います。
このようなもの:
ProvinceID #1
RegionID # 1: 12000
RegionID # 2: 30000
ProvinceID #2
RegionID #1: 14000
RegionID #: 145000
これが私がしたことです グローバル配列 int[,] census; を宣言します。
フォームで初期化します initialize census = new int[624,3];
ここに私のインサートがあります
try
{
// declare variables
int prov, region, population;
prov = Convert.ToInt32(txtProvinceID.Text);
region = Convert.ToInt32(txtRegionID.Text);
population = Convert.ToInt32(txtPopulation.Text);
census[counter, 0] = prov;
census[counter, 1] = region;
census[counter, 2] = population;
counter++;
MessageBox.Show("Population " + txtPopulation.Text.ToString() + " saved for Province #" + txtProvinceID.Text.ToString()
+ " , Region #" + txtRegionID.Text.ToString(), "Success!");
txtRegionID.Clear();
txtProvinceID.Clear();
txtPopulation.Clear();
txtProvinceID.Focus();
}
catch (Exception ex)
{
if (ex.Message == "Input string was not in a correct format.")
{
MessageBox.Show("Please enter a numeric value", "Error");
}
else
{
MessageBox.Show(ex.Message, "Error");
}
}
これは、データを取得してファイルに保存するためのコードです
string output = "";
try
{
for (int rows = 0; rows < census.GetLength(0); rows++)
{
for (int columns = 0; columns < census.GetLength(1); columns++)
{
if (census[rows, columns] != 0)
{
if (columns == 0)
{
output += "Province ID #" + census[rows, columns];
}
else if (columns == 1)
{
output += "Region ID #" + census[rows, columns] + ": ";
}
else if (columns == 2)
{
output += census[rows, columns] + "\n";
}
}// END if census[rows, coloumns]!=0
}// END for coloumns
}//END for(int row =0
// save the data to a text file
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "untitled";
sfd.Filter = "Text (*.txt)|*.txt|Word Doc (*.doc)|*.doc";
sfd.DefaultExt = "txt";
sfd.AddExtension = true;
sfd.ShowDialog();
FileStream sf = new FileStream(sfd.FileName, FileMode.Create);
StreamWriter sw = new StreamWriter(sf);
sw.Write(output);
sw.Close();
}
catch (Exception)
{
}