0

This is the instruction: returns an int array where array[0] is the number of unused spaces This is the code I have so far but I am not sure if I am doing it right (or what I need to return in the method)

public int[] counts()
   {
       int count=0;

       for(int i=0; i<array.length;i++)
       {
           for (int j=0; j<array.length; j++)
           {
           if (array[i][j] == 0)
               {
                   count = 0;
               }
            }
        }
       return;
   }
LaurentG
  • 9,745
  • 8
  • 44
  • 61
  • 1
    1) you need to create and fill an int[] array variable before your function ends, since you need to return it. For help on that, see https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java. 2) You are using a var called array, but have never defined it. What is it and where did it come from. 3) If you need the length of a 2D array, see https://stackoverflow.com/questions/7367218/getting-the-length-of-two-dimensional-array 4) in your loop you probably want count++. 5) what does "unused spaces" mean? Seems like you want to count values of 0 in a 2D arr – Ernie Thomason Oct 31 '19 at 04:56

2 Answers2

0

public int[] counts() the int[] is the return type. The method wants you to return a one-dimensional array. What I am understanding from your question and the code is that when a space in the two-dimensional array is 0, you'll want to increment the counter by one, but you are not incrementing the counter you are just setting it to zero. You'll want to change the,

count = 0;

to

count++; //it's the same as count += 1 or count = count + 1

and return it as a one-dimensinal array:

return new int[] {count};
Dr. Confused
  • 76
  • 1
  • 6
0

Are you sure you've understood the problem correctly? If you are returning a single number (i.e. the number of 0s in a 2D array) then it really doesn't make a lot of sense to return it as an array with a single element. I think it's possible that what you are being asked to do is to return an array that has the number of 0s in the array with the corresponding index. That would make more sense to me.

If that's the case then the solution would look something like:

int[] getCounts(int[][] array) {
    int[] result = new int[array.length];
    for (int i = 0; i < array.length; i++) {
        result[i] = 0;
        for (int val: array[i]) {
            if (val == 0)
                result[i]++;
        }
    }
    return result;
}
sprinter
  • 24,103
  • 5
  • 40
  • 71