@embiid

Как изменить ошибку: «Индекс находится вне границы массива»?

Пожалуйста, помогите пофиксить проблему с методом EnterMatrix.
Именно в:
MATRIX[j, k] = int.Parse(Console.ReadLine());

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Matrix {
    int row, column;
    int[,] MATRIX;

    public int ROW {
        get { return row; }
        set { row = value; }
    }

    public int COLUMN {
        get { return column; }
        set { column = value; }
    }

    public Matrix() {

    }

    public Matrix(int row, int column) {
        this.row = ROW;
        this.column = COLUMN;

        MATRIX = new int[this.COLUMN, this.ROW];
    }

    public void EnterMatrix() {
        Console.Write("Enter the numbers of matrix columns: ");
        COLUMN = int.Parse(Console.ReadLine());
        Console.Write("Enter the numbers of matrix rows: ");
        ROW = int.Parse(Console.ReadLine());

        for (int j = 0; j < COLUMN; j++) {
            for (int k = 0; k < ROW; k++) {
                Console.Write("For matrix cell -> " + (j + 1) + ":" + (k + 1) + " - ");
                MATRIX = new int[j, k];
                MATRIX[j, k] = int.Parse(Console.ReadLine());
            }
        }
    }

    public void DisplayMatrix() {
        Console.Write("The matrix is: ");
        for (int j = 0; j < COLUMN; j++) {
            for (int k = 0; k < ROW; k++) {
                Console.WriteLine("{0}\t", MATRIX[j, k]);
            }
        }
    }

    ~Matrix() {
        Console.WriteLine("Matrix has been denied.");
    }
}

class Vector : Matrix {
    public Vector(int row, int column) {
        
    }

    

    ~Vector() {
        Console.WriteLine("Vector has been denied.");
    }
}

class Program {
    static void Main() {
        Matrix MATRIX = new Matrix();
        MATRIX.EnterMatrix();
        MATRIX.DisplayMatrix();
    }
}
  • Вопрос задан
  • 837 просмотров
Решения вопроса 1
MATRIX = new int[j, k];
MATRIX[j, k] = int.Parse(Console.ReadLine());

В цикле Вы каждый раз выделяете в памяти новый массив [j, k] - соответственно, от 0 до (j - 1) и от 0 до (k - 1), а потом обращаетесь к ячейке [j, k].
Нужно вынести создание массива за циклы
Console.Write("Enter the numbers of matrix columns: ");
COLUMN = int.Parse(Console.ReadLine());
Console.Write("Enter the numbers of matrix rows: ");
ROW = int.Parse(Console.ReadLine());
MATRIX = new int[COLUMN, ROW];
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
AlexanderYudakov
@AlexanderYudakov
C#, 1С, Android, TypeScript
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы