我有一项任务,我们必须创建一个项目,查看两个城市之间的行车距离。
使用两个包含城市名称的下拉列表。标记一个列表“出发”和另一个“目的地”。使用“查找”按钮计算距离。将距离存储在二维表中。
我开始这样做了,但我注意到我将不得不重复代码太多次了,我知道有更好的方法来做到这一点。这就是我需要帮助的地方。
有没有办法在这个问题中使用For循环?如果有,我该怎么做?
Option Strict On
Public Class Form1
Dim Distance(,) As Long = {{0, 1004, 1753, 2752, 3017, 1520, 1507, 609, 3155, 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}}
Private Sub LookUpBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LookUpBtn.Click
If ComboBox1.SelectedIndex = 0 And ComboBox2.SelectedIndex = 0 Then
DistanceLbl.Text = (Distance(0, 0).ToString & " miles")
ElseIf ComboBox1.SelectedIndex = 0 And ComboBox2.SelectedIndex = 1 Then
DistanceLbl.Text = (Distance(0, 1).ToString & " miles")
ElseIf ComboBox1.SelectedIndex = 0 And ComboBox2.SelectedIndex = 2 Then
DistanceLbl.Text = (Distance(0, 2).ToString & " miles")
ElseIf ComboBox1.SelectedIndex = 0 And ComboBox2.SelectedIndex = 3 Then
DistanceLbl.Text = (Distance(0, 3).ToString & " miles")
ElseIf ComboBox1.SelectedIndex = 0 And ComboBox2.SelectedIndex = 4 Then
DistanceLbl.Text = (Distance(0, 4).ToString & " miles")
ElseIf ComboBox1.SelectedIndex = 0 And ComboBox2.SelectedIndex = 5 Then
DistanceLbl.Text = (Distance(0, 5).ToString & " miles")
ElseIf ComboBox1.SelectedIndex = 0 And ComboBox2.SelectedIndex = 6 Then
DistanceLbl.Text = (Distance(0, 6).ToString & " miles")
ElseIf ComboBox1.SelectedIndex = 0 And ComboBox2.SelectedIndex = 7 Then
DistanceLbl.Text = (Distance(0, 7).ToString & " miles")
ElseIf ComboBox1.SelectedIndex = 0 And ComboBox2.SelectedIndex = 8 Then
DistanceLbl.Text = (Distance(0, 8).ToString & " miles")
ElseIf ComboBox1.SelectedIndex = 0 And ComboBox2.SelectedIndex = 9 Then
DistanceLbl.Text = (Distance(0, 9).ToString & " miles")
End If
End Sub
End Class
答案 0 :(得分:2)
直接使用SelectedIndex
作为数组的偏移量:
Distance(ComboBox1.SelectedIndex, ComboBox2.SelectedIndex)
您可能需要对案例进行测试"没有选择"其中SelectedIndex为-1并且尝试访问数组中的偏移量将获得ArgumentOutOfRangeException。
答案 1 :(得分:1)
很高兴您注意到For循环的重复和思考,但实际上您并不需要这个问题。
你做的相当于:
可以更简单地表达为:
因此,对于您的真实代码,它就像这样简单:
DistanceLbl.Text = (Distance(
ComboBox1.SelectedIndex,
ComboBox2.SelectedIndex).ToString & " miles")
答案 2 :(得分:0)
在我看来,您只需要在访问阵列时使用组合框中的值。这可以替换代码的整个If..Elseif部分。
DistanceLbl.Text = (Distance(ComboBox1.SelectedIndex, ComboBox2.SelectedIndex).ToString & " miles")