Reputation: 397
I'm writing a program where I want to be able to 'clear' the array below when a particular method is called. By changing all of the values to zero. I understand how to change a single value in an array, but am unsure what sort of a for loop to write to change them all.
int[][] array = {{1,2,3,4},{5,6,7,8}};
I've tried a few things, but can only seem to be able to change some of the values instead of all of them. For example, the following code below only changed the first two elements of each row.
public static void main(String[] args) {
int[][] array = {{1, 2, 3, 4}, {5, 6, 7, 8}};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++)
array[i][j] = 0;
}
for (int[] x : array) {
for (int y : x) {
System.out.print(y + " ");
}
System.out.println();
}
}
I'm really new to Java and am not great at for loops, so it would be great to have some help on writing this as a for loop.
Please let me know if I need to provide any more information!
Upvotes: 2
Views: 855
Reputation: 26
You can also use Arrays.fill in java
for (double[] row: array) {
Arrays.fill(row, 0.0);
}
Upvotes: 1
Reputation: 51
for (int i = 0; i < array.length; i++) {
for (int j = 0; j< array[i].length; j ++)
array[i][j] = 0;
}
second loop not right, try this....
Upvotes: 1