I can’t fill a matrix

Asked

Viewed 165 times

1

When I put fixed values in the size of the matrix I can fill it, but when I try to capture the values in matrices a message like this appears:

The index was outside the matrix boundaries

      ` int a = 0, b = 0;
        double[ , ] test = new double[a , b];

        Console.Write("Linha: ");
        a = int.Parse(Console.ReadLine());

        Console.Write("Coluna: ");
        b = int.Parse(Console.ReadLine());

        for (int i = 0; i < a; i++)
        {  
            for (int j = 0; j < b ; j++)
            {
               Console.Write("Digite um valor: "); 
               test[i , j] = double.Parse(Console.ReadLine()); 
            }

        }

        Console.WriteLine("\n\n ");

        for (int i = 0; i < a; i++)
        {
            for (int j = 0; j < b; j++)
            {
                Console.Write(test[i, j] + " ");
            }
            Console.WriteLine(" ");
        }

        Console.ReadKey();`

1 answer

3


The problem is that declaring the matrix before establishing the value first asks for the values, then declares it. It makes no sense to create the foundation of a house that you don’t know what size and how many rooms it will have.

The code has other errors. An improved version, simplifying and giving more meaningful names, and it would be like this (I simply closed if a typing is wrong, but can do the error handling you want there):

using static System.Console;

public class Program {
    public static void Main() {
        Write("Linha: ");
        if (!int.TryParse(ReadLine(), out var linhas)) return;
        Write("Coluna: ");
        if (!int.TryParse(ReadLine(), out var colunas)) return;
        var matriz = new double[linhas, colunas];
        for (int i = 0; i < linhas; i++) {  
            for (int j = 0; j < colunas; j++) {
                Write("Digite um valor: ");
                if (!double.TryParse(ReadLine(), out var valor)) return;
                matriz[i, j] = valor; 
            }
        }
        WriteLine("\n\n");
        for (int i = 0; i < linhas; i++) {
            for (int j = 0; j < colunas; j++) Write(matriz[i, j] + " ");
            WriteLine(" ");
        }
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

See the importance of using the TryParse().

  • Thank you very much, I did not find any tutorial that would teach this, thank you very much.

  • 2

    Because the ideal is not to follow tutors, it is to learn in a structured way. To understand everything that is taking place in the code is to gain knowledge step by step. And tutors are created to burn stages, which is bad for learning.

  • Thanks for the tip.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.