I can not fill an array

1

When I put fixed values in the array size I can fill it up, but when I try to capture the values in arrays a message like this appears:

  

The index was outside the bounds of the array

      ' 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();'
    
asked by anonymous 13.10.2018 / 16:43

1 answer

3

The problem is that declaring the array before setting the value, first requests the values, then declaring it. It does not make sense to build the foundation of a home that you do not know what size and how many rooms you will have.

The code has other errors. An improved version, simplifying and giving more meaningful names, and it would be like this (I just closed it if typing is wrong, but you can do whatever error treatment 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(" ");
        }
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .

See the importance of using TryParse() .

    
13.10.2018 / 16:58