Declare Two-Dimensional Array - Clarification

460 views Asked by At

I am currently taking Java lessons, and the course is explaining two-dimensional arrays. The first method to declaring that type of variable would be to create a constant as arguments for how many rows and columns will be in my two-dimensional array. Then, I just used a nested for-loop to give random numbers to those particular rows, and columns.

The second method to declare AND initialize a two-dimensional array would be "int[][] nums" line below. I know that it has 3 rows. It's basically similar to putting a list in a bigger list, but how many columns are in the "nums" array? There may be a simple answer, but I am a little confused right now. Thank you for the assistance.

import java.util.Random; //Importing Class from Package

public class Chap15Part4
{
    public static void main(String[] args)
    {
        final int rows = 5; //Constant
        final int cols = 5; //Constant
        int[][] numbers = new int[rows][cols]; //Declaring 2-D Array with       constants as arguments
        Random rand = new Random(System.currentTimeMillis()); //Seeding Random Number Generator
        for(int r = 0; r < rows; ++r) //Nested for-loop to assign numbers to elements
            for (int c = 0; c < cols; ++c)
                numbers[r][c] = rand.nextInt(101); 

        int[][] nums = {{10,20,30,40}, {20,30,40,50}, {30,40,50,60}}; //Declaring & Initializing 2-D Array
    }

}
2

There are 2 answers

1
haley On BEST ANSWER

There are four columns. The matrix will look like this, so you can count the columns easily:

{{10, 20, 30, 40},
 {20, 30, 40, 50},
 {30, 40, 50, 60}}
1
River On

There will be 4 columns as each sub-array item has 4 items.

Imagine stacking each item in brackets on top of the next so that the final array will look like:

10 20 30 40
20 30 40 50
30 40 50 60