【发布时间】:2018-10-25 00:38:32
【问题描述】:
所以问题是
“创建一个查找两个城市之间的行车距离的项目。使用两个包含城市名称的下拉列表。标记一个列表出发地和另一个目的地。使用查找按钮来计算距离。 将距离存储在二维表中。”
有没有更好的使用for循环编码的方法
好的,下面是代码
private void lookUpButton_Click(object sender, EventArgs e)
{
int [,] miles = { {0,1004, 1753, 2752, 3017,1520, 1507,609, 3115,448},
{1004,0, 921,1780, 2048, 1397, 919,515 , 2176,709},
{ 1753,921, 0,1230, 1399,1343, 517,1435, 2234,1307},
{ 2752,1780,1230,0 , 272,2570, 1732,2251, 1322,2420},
{3017,2048 , 1399,272, 0,2716, 1858,2523, 1278,2646},
{ 1520,1397, 1343,2570, 2716,0, 860,1494, 3447,1057},
{ 1507,919, 517,1732, 1858,860, 0,1307, 2734,1099},
{ 609,515, 1435,2251, 2523,1494, 1307,0, 2820,571},
{ 3155,2176, 2234,1322, 1278,3447, 2734,2820, 0,2887},
{ 448,709, 1307,2420, 2646,1057, 1099,571,2887,0 }
};
//var distance = miles[txtDeparture.SelectedIndex,txtDeparture.SelectedIndex];
// alot of if statments
if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 0))
{
var distance = miles[0, 0];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 1))
{
var distance = miles[0, 1];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 2))
{
var distance = miles[0, 2];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 3))
{
var distance = miles[0, 3];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 4))
{
var distance = miles[0, 4];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 5))
{
var distance = miles[0, 5];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 6))
{
var distance = miles[0, 6];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 7))
{
var distance = miles[0, 7];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 8))
{
var distance = miles[0, 8];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 9))
{
var distance = miles[0, 9];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 0) && (txtDestination.SelectedIndex == 10))
{
var distance = miles[0, 10];
txtDistancebox.Text = distance.ToString();
}
else if ((txtDeparture.SelectedIndex == 1) && (txtDestination.SelectedIndex == 0))
{
var distance = miles[1, 0];
txtDistancebox.Text = distance.ToString();
}
}
【问题讨论】:
-
如果您的代码有效并且您只是在寻找改进它的建议,那么您的帖子属于 Code Review。
-
您应该在代码中看到一个模式,并意识到您可以将硬编码的索引值替换为
if条件中的对象... -
另外,
txt前缀通常用于 TextBox,而不是 ComboBox... -
您也可以考虑在类级别存储数组,而不是在每次单击按钮时重新创建它。
-
@Rufus OP 2 小时前的问题也有相同的答案。我想知道为什么OP第二次发布它。