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