Java 如何创建一个将二维数组作为参数并显示包含最多零的行的索引的方法?
如何创建一个将二维数组作为参数并显示包含最多零的行的索引的方法?我的程序不需要编译。它只是显示了一个不正确的结果。countZeros方法统计每行中的零数。我需要将每个计数与下一个计数进行比较,所以我创建了count和count2。较大计数的位置将存储在rowNum中。我不确定我做错了什么。我认为可能是索引错误 这是我的密码:Java 如何创建一个将二维数组作为参数并显示包含最多零的行的索引的方法?,java,arrays,count,location,2d,Java,Arrays,Count,Location,2d,如何创建一个将二维数组作为参数并显示包含最多零的行的索引的方法?我的程序不需要编译。它只是显示了一个不正确的结果。countZeros方法统计每行中的零数。我需要将每个计数与下一个计数进行比较,所以我创建了count和count2。较大计数的位置将存储在rowNum中。我不确定我做错了什么。我认为可能是索引错误 这是我的密码: public class P118 { public static void main(String[]args) { int[][
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;
}
}
试试这个:
public static int rowWithMostZeros(int[][] arr) {
if (arr == null || arr.length < 1) {
return -1;
}
int rowWithMostZeros = 0;
int count = countZeros(arr[0]);
for (int i = 1; i < arr.length; i++) {
int count2 = countZeros(arr[i]);
if (count2 > count) {
rowWithMostZeros = i;
}
}
return rowWithMostZeros;
}
public static int countZeros(int[] arr) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == 0) {
count += 1;
}
}
return count;
}
计算发生次数的任何代码都可以使用以下方法: 首先使用第一行或无效数据作为“max” 检查其他值是否更大。如果是,请更换 “最大值”计算该值的金额和“行号”。 以下代码首先将值设置为第一行的最大值,然后检查其他行是否有更多的零:
public static int rowWithMostZeros(int[][]arr)
{
int mostZeroCount = countZeros(arr[0];
int rowNum = 0;
for(int row = 1; row<arr.length;row++)
{
int count = countZeros(arr[row]);
if(count>mostZeroCount)
{
rowNum = row;
mostZeroCount = count;
}
}
return rowNum;
}
原始方法的问题是,它总是将count设置为下一个值,该值大于一个0,而不与之前看到的实际最大值0进行比较。因此,在最后,它只返回至少有一个0的最后一行,在本例中是第2行,第三行您应该使用变量count2来存储到目前为止所有行中的最大零数,以便与下一行进行比较。为了做到这一点,您需要在if块内为其分配当前计数,以防计数大于count2。为了更加清晰,我在下面使用maxCount和currentCount重新设计了您的代码。代码中的第二个循环是不必要的,我真的不明白你为什么这么做
谢谢你的解释。我明白我的错误了。
public static int rowWithMostZeros(int[][]arr){
int currentCount = 0, maxCount = 0, rowNum = -1;
for(int row = 0; row maxCount){
maxCount = currentCount;
rowNum = row;
}
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;
}