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 = '~';
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.
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.
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.
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, '~');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With