Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill two-dimensional array using java enhanced loop?

Tags:

java

arrays

Basically, I am trying this, but this only leaves array filled with zeros. I know how to fill it with normal for loop such as

for (int i = 0; i < array.length; i++)

but why is my variant is not working? Any help would be appreciated.

char[][] array = new char[x][y];
for (char[] row : array)
    for (char element : row)
        element = '~';
like image 746
evgeniuz Avatar asked Apr 14 '10 09:04

evgeniuz


People also ask

Can you use an enhanced for loop on a two-dimensional array?

Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array.

Can you use enhanced for loop on array?

Use the enhanced for each loop with arrays whenever you can, because it cuts down on errors. You can use it whenever you need to loop through all the elements of an array and don't need to know their index and don't need to change their values.

How do you loop a 2D array?

To loop over two dimensional array in Java you can use two for loops. Each loop uses an index. Index of outer for loop refers to the rows, and inner loop refers to the columns. You can then get each element from the array using the combination of row and column indexes.


1 Answers

Thirler has explained why this doesn't work. However, you can use Arrays.fill to help you initialize the arrays:

    char[][] array = new char[10][10];
    for (char[] row : array)
        Arrays.fill(row, '~');
like image 118
bruno conde Avatar answered Oct 10 '22 05:10

bruno conde