Kronos
Kronos

Reputation: 13

User input to multi-dimensional array (column)

I have an array:

 [ 0  0
   1  0
   2  0
   3  0
   4  0
   5  0 ]

How do I specify where the user input (using scanner) will go to in the array? I would like to add an integer to each position of the second column.

Upvotes: 0

Views: 1952

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213193

For an array of array, to get the number of rows, you use the length of your array.

For e.g, for this array: -

int[][] arr = new int[3][4];

arr.length gives you number of rows in the array, i.e. 3. So, run a loop from 0 to arr.length, to access each row.

Now, to access the 2nd column of each row, you can do arr[i][1] in your loop: -

for (int i = 0; i < arr.length; i++) {
    arr[i][1] = ...;  // your 2nd column for each row
}

Also, to get user input to fill your 2nd column for each row, you have to read input for each row. So, you can guess where you need to read the user input - In outer loop, or in inner loop?

Upvotes: 1

Related Questions