Results 1 to 4 of 4

Thread: [RESOLVED] Finding an empty cell in an array

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jul 2005
    Location
    Chicago
    Posts
    202

    Resolved [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.

  2. #2
    Addicted Member SpS's Avatar
    Join Date
    Jul 2005
    Posts
    201

    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.

  3. #3
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    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

  4. #4

    Thread Starter
    Addicted Member
    Join Date
    Jul 2005
    Location
    Chicago
    Posts
    202

    Re: Finding an empty cell in an array

    Thanks!
    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
  •  



Click Here to Expand Forum to Full Width