How do I create a method that takes a two-dimensional array as a parameter and displays the index of the row with the most zeros? The program I have does compile. It just displays an incorrect result. The method countZeros() counts the number of zeros in each row. I need to compare each count with the next, so I created count and count2. The location of the greater count will be stored in rowNum. I’m not sure what I am doing wrong. I think it may be indexing incorrectly.
Here is my code:
public class P118
{
public static void main(String[]args)
{
int[][]num = {{0,3,6,0,0}, {1,3,8,9,8}, {9,9,9,0,8}, {3,7,9,9,9}};
System.out.print(rowWithMostZeros(num));
}
public static int rowWithMostZeros(int[][]arr)
{
int count = 0, count2 = 0, rowNum = -1;
for(int row = 0; row<arr.length;row++)
{
count = countZeros(arr[row]);
if(count>count2)
{
rowNum = row;
}
}
for(int i=0; i<arr.length;i++)
{
count2 = countZeros(arr[i]);
}
return rowNum;
}
public static int countZeros(int[]x)
{
int count = 0;
for(int i = 0; i<x.length;i++)
{
if(x[i]==0)
{
count++;
}
}
return count;
}
}
Try this: