[RESOLVED] Finding an empty cell in an array
Hi guys. I am very new to java and I have a question. I have created a 2-dimensional array filled with a bunch of zeroes. The user can input values into the cells, overwriting the zeroes. My question is how do I determine the location of the first cell on the first row with a value of 0? Below is an example array. I want to return the number 3 (the index of the first zero).
1 2 3 0 4 5
1 2 3 4 5 6
1 2 3 4 5 6
Re: Finding an empty cell in an array
Have two for loops and compare every value of array with 0 and if match found do what is required.
eg code
Code:
for(int i=...){
for(int j=...){
if(0==array[i][j])
return array[i][j];
else{
...
}
}
}
Re: Finding an empty cell in an array
This is your full code to return the "3" only:
Code:
public class Test {
public static void main(String args[]) {
int a[][] = {
{
1, 2, 3, 0, 4, 5}
, {
1, 2, 3, 4, 5, 6}
, {
1, 2, 3, 4, 5, 6}
};
System.out.println(findEmptyCell(a));
}
private static int findEmptyCell(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] == 0) {
return j;
}
}
}
return -1;
}
}
Re: Finding an empty cell in an array