Search code examples
javaarraysfor-loopnestednested-loops

Exception when trying to print all values in a 2D array using a for loop. Need help understanding the Nested for loop too


I am currently learning beginning to learn Java, using BroCode for Uni, learning how to use For loops to print all values in the 2D array. The code is coming up with an exception in thread: Index 3 is out of bounds for length 3 at Arrays2D.main.

Also I am unsure what the nested for loop is exactly saying, anyone able to walk me through it?

{
    //2D Arrays = an array in an array

    String[][] cars = {
            {"Toyota", "Mazda", "Subaru"},
            {"Ferrari", "Mercedes", "Porsche"},
            {"Tesla", "Ford", "Hyundai"}
    };
    //[how many arrays][how many elements in each array]
    
    for(int i = 0; i < cars.length; i++)
    {
        System.out.println();
        for(int j = 0; j < cars[i].length; i++)
        {
            System.out.println(cars[i][j] + ", ");
        }
    }
}

Copied code from video, not sure where it went wrong? Pretty much just expecting it to print all values in cars.


Solution

  • You should change i++ to j++ in your inner loop.

       for (int i = 0; i < cars.length; i++) {
            System.out.println();
            for (int j = 0; j < cars[i].length; j++) {
                System.out.println(cars[i][j] + ", ");
            }
        }
    

    The outer loop means traversing the array by row, and the inner by column. cars[i][j]represents the car in row i, column j.