简体   繁体   English

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

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

so I tried making a program in c# using a 2D array to calculate the distance between two cities that are selected from a combo box. 所以我尝试使用2D数组在c#中编写程序,以计算从组合框中选择的两个城市之间的距离。 Here's the code. 这是代码。

    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]);
    }

however, when i try to select two cities and press the button to calculate and display them in a label, it crashes and I get a message saying 但是,当我尝试选择两个城市并按按钮进行计算并将它们显示在标签中时,它崩溃了,并且我收到一条消息说

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in cityHW.exe cityHW.exe中发生了'System.IndexOutOfRangeException'类型的未处理异常

what am I doing wrong? 我究竟做错了什么?

Array initialization needs improvement. 数组初始化需要改进。 Each element of array should be in double quotes. 数组的每个元素都应该用双引号引起来。 Try below. 请尝试以下。 I have used text editor rather than IDE to solve it. 我使用文本编辑器而不是IDE来解决它。 So please check for any syntax error (just in case I missed out any matching double quotes. 因此,请检查是否存在语法错误(以防万一我错过了所有匹配的双引号。

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" } };

Each of your "inner" arrays had a single element: 您的每个“内部”数组都有一个元素:

{
    // 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" }
}

Note in particular that adding the commas inside the string doesn't create additional elements - it's just a single string with a bunch of commas in it. 特别要注意的是,在字符串中添加逗号不会创建其他元素-它只是一个字符串,其中包含一堆逗号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM