Visualizzazione dei risultati da 1 a 2 su 2
  1. #1

    [C#] Stampa array multidimensionale ed errore IndexOutOfRangeException

    ciao!

    ottengo un errore quando provo a stampare i valori di questo array:
    codice:
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[,] arrayMulti = new int[4, 2] {
                    {1, 5}, {5, 4}, {0, 2}, {8, 7}
                };
    
                for (int i = 0; i < 5; i++)
                {
                    for (int j = 0; j < 2; j++)
                    {
                        Console.WriteLine("a[{0},{1}] = {2}", i, j, arrayMulti[i, j]); // ERRORE
                    }
                }
                Console.ReadKey();
            }
        }
    }
    l'errore è questo:
    codice:
    a[0,0] = 1
    a[0,1] = 5
    a[1,0] = 5
    a[1,1] = 4
    a[2,0] = 0
    a[2,1] = 2
    a[3,0] = 8
    a[3,1] = 7
    
    Eccezione non gestita: System.IndexOutOfRangeException: Indice oltre i limiti de
    lla matrice.
       in ConsoleApp1.Program.Main(String[] args) in Program.cs:riga 17
    Premere un tasto per continuare . . .
    sinceramente non sto capendo il perchè.
    mi sfugge qualcosa sulla formattazione dell'output mi sa!

  2. #2
    ho risolto così:
    codice:
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                int[,] arrayMulti = new int[4, 2] {
                    {1, 5}, {5, 4}, {0, 2}, {8, 7}
                };
                int rowLength = arrayMulti.GetLength(0);
                int colLength = arrayMulti.GetLength(1);
    
                for (int i = 0; i < rowLength; i++)
                {
                    for (int j = 0; j < colLength; j++)
                    {
                        Console.WriteLine(string.Format("record[{0},{1}] ", i, j, arrayMulti[i, j]));
                    }
                }
                Console.ReadKey();
            }
        }
    }

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.