|
-
Feb 18th, 2006, 08:41 PM
#1
Thread Starter
Addicted Member
[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
A programmer is a person who fixes a problem you did not know you had in a way that you cannot understand.
-
Feb 19th, 2006, 07:40 AM
#2
Addicted Member
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{
...
}
}
}
Last edited by SpS; Feb 19th, 2006 at 07:43 AM.
#Appreciate others by rating good posts !!
#The Software Peter Principle is in operation when unwise developers "improve" and "generalize" the software until they themselves can no longer understand it, then the project slowly dies.
#People who are still ignorant of their ignorance are dangerous.
-
Feb 19th, 2006, 07:53 AM
#3
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;
}
}
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Feb 19th, 2006, 12:22 PM
#4
Thread Starter
Addicted Member
Re: Finding an empty cell in an array
A programmer is a person who fixes a problem you did not know you had in a way that you cannot understand.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|