带有显示距离的组合框的 c# 中的数组程序不断崩溃。为什么?

array program in c# with combo boxes that displays distance keeps crashing. why?

所以我尝试使用二维数组在 c# 中编写一个程序来计算从组合框中 selected 的两个城市之间的距离。这是代码。

    private void btnCalculate_Click(object sender, EventArgs e)
    {
         string[,] distance = {
                      { "0, 1004, 1753, 2752, 3017, 1520, 1507" },
                      { "1004, 0, 921, 1780, 2048, 1397, 919" },
                      { "1753, 921, 0, 1230, 1399, 1343, 517" },
                      { "2752, 1780, 1230, 0, 272, 2570, 1732" },
                      { "3017, 2048, 1399, 272, 0 2716, 1858" },
                      { "1520, 1397, 1343, 2570, 2716, 0, 860" },
                      { "1507, 919, 517, 1732, 1858, 860, 0" }
        };

        lblDistance.Text = (distance[cboStartPoint.SelectedIndex, cboDestination.SelectedIndex]);
    }

然而,当我尝试 select 两个城市并按下按钮计算并在标签中显示它们时,它崩溃了,我收到一条消息说

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in cityHW.exe

我做错了什么?

数组初始化需要改进。 数组的每个元素都应该用双引号引起来。 试试下面。我使用文本编辑器而不是 IDE 来解决它。所以请检查是否有任何语法错误(以防我遗漏任何匹配的双引号。

string[,] distance = { { "0", "1004", "1753", "2752", "3017", "1520", "1507" },
                  { "1004", "0", "921", "1780", "2048", "1397", "919" },
                  { "1753", "921", "0", "1230", "1399", "1343", "517" },
                  { "2752", "1780", "1230", "0", "272", "2570", "1732" },
                  { "3017", "2048", "1399", "272", "0 2716", "1858" },
                  { "1520", "1397", "1343", "2570", "2716", "0", "860" },
                  { "1507", "919", "517", "1732", "1858", "860", "0" } };

您的每个 "inner" 数组都有一个元素:

{
    // This array has a single item
    { "0, 1004, 1753, 2752, 3017, 1520, 1507" },
    // Also has a single item
    { "1004, 0, 921, 1780, 2048, 1397, 919" }
}

请特别注意,在字符串中添加逗号不会创建额外的元素 - 它只是一个包含一堆逗号的字符串。