1

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
    }

}
3
  • 4
    There are "four columns" in nums. However, keep in mind that a 2-dimensional array is simply an array where every element of that array is itself another array. So the structure need not be square. That is, nums[0] may be an array of size 3, but nums[1] may be an array of size 4 Commented Jun 10, 2015 at 16:07
  • 1
    4 columns...as every list as 4 elements. You can keep these small lists stacked and see it like {10,20,30,40} {20,30,40,50} {30,40,50,60} Commented Jun 10, 2015 at 16:08
  • Thank you for the help! I would say that you should read more about how nested for-loops work in order to better understand the first method, too. Commented Jun 10, 2015 at 17:02

2 Answers 2

3

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}}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The way you typed it out makes a lot more sense.
1

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

1 Comment

This was also very helpful. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.