Почему эта ошибка появляется в моем коде C#?
после компиляции моего кода я получаю следующую ошибку
Index was outside the bounds of the array.
этот код выглядит следующим образом:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace CW2 { class LinkedNode { public char val; public LinkedNode next; public LinkedNode prev; public LinkedNode top; public LinkedNode bottom; //Default Constructor public LinkedNode() { val = ' '; next = null; prev = null; top = null; bottom = null; } //Constructor with parameter public LinkedNode(char value) { val = value; next = null; prev = null; top = null; bottom = null; } static void Main(string[] args) { //path to the file. string path = @"C:\Users\Bradleigh\source\repos\MazeGame\\4-general-7x8.txt"; string[] lines = System.IO.File.ReadAllLines(path); //First line holds row and column information string[] line = lines[0].Split(' '); int row = Convert.ToInt32(line[0]); int col = Convert.ToInt32(line[1]); //holding 0s 1s and starting point 's' and exit point 'o' char[,] maze_board = new char[row, col]; for (int i = 1; i < lines.Length; i++) { //String to char array char[] arr = lines[i].ToCharArray(); for (int j = 0; j < arr.Length; j++) maze_board[i - 1, j] = arr[j]; } //Display the maze now for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) Console.Write(maze_board[i, j] + " "); Console.WriteLine(); //Console.WriteLine(); } //An array of nodes to create a four-way linked list for traversal of the maze LinkedNode[,] node = new LinkedNode[row, col]; //Holds the start coords of the maze entrance int startX = -1, startY = -1; //Nested for loops that index and populate a 2d dimensional array which will be the maze for (int i = 0; i < lines.Length - 1; i++) { //Converts the maze file to an array of characters char[] arr = lines[i + 1].ToCharArray(); for (int j = 0; j < arr.Length; j++) { //Sets the array of nodes to be the number of tiles in the maze node[i, j] = new LinkedNode(arr[j]); //If the start of the maze is found, store the array coordinates if (node[i, j].val == 's' || node[i, j].val == 'o') { startX = i; startY = j; } //Checks that the left side of the maze tile is inside the array bounds if (j - 1 >= 0) { //creates a link between the previous and next nodes node[i, j].prev = node[i, j - 1]; node[i, j - 1].next = node[i, j]; } //Does the same but with the top and bottom tiles if (i - 1 >= 0) { node[i, j].top = node[i - 1, j]; node[i - 1, j].bottom = node[i, j]; } } Stack stack = new Stack(); new Stack<linkednode>(); //adds starting square to stack stack.Push(node[startX, startY]); //while the stack count is more than 0 pop current while (stack.Count > 0) { var current = stack.Pop(); //marks visited with v node[startX, startY].val = 'v'; //Queue q = new Queue(); } } } } }
ожидаемый результат примерно такой:
Цитата:Пожалуйста, введите файл лабиринта: 4x6-maze.txt
01010e
110101
011101
11s000
Нажмите клавишу Enter, чтобы продолжить...
01010e
110101
011101
11sv00
Нажмите клавишу Enter, чтобы продолжить...
01010e
110101
011101
11svv0
...
0101ve
1101v1
0111v1
11сввв
Нажмите клавишу Enter, чтобы продолжить...
Цель достигнута...
Путь показан с помощью "3"...
01013e
110131
011131
11с33в
Что я уже пробовал:
Я не знаю, что попробовать, так как эта ошибка является неожиданной.
F-ES Sitecore
Вы получаете эту ошибку, когда получаете доступ к элементу в массиве, который не существует. Если у вас есть массив с двумя вещами
a[0] = 1
a[1] = 2
и если вы попытаетесь получить доступ к[2], то получите эту ошибку. Используйте отладчик, чтобы выяснить, в какой строке он встречается, и проблема заключается либо в том, что вы обращаетесь к данным, которых там нет, но которые должны быть (вы обращаетесь к A[2], поскольку в массиве должно быть три элемента, но их нет), либо вы обращаетесь к данным, к которым вы не должны обращаться (вы обращаетесь к A[i], а "i" неожиданно 2). После того, как вы это выяснили, пройдите через код, чтобы увидеть, что он делает, и выяснить, в чем заключается проблема. Мы действительно не можем сделать это для вас.