java - 计算数组中的负数

标签 java arrays multidimensional-array

我正在尝试查找二维数组(方阵)中负数的计数。在矩阵中,如果您从上到下并向左书写数字增加。这里的逻辑是从最后一列开始并向左移动。如果找到负数,则增加行索引并以相同的方式进行直到最后一行。我在 java 代码中收到错误,但在 python 中没有。

public class O_n 

{

public static void main(String[] args)

{

    int firstarray[][] = {{-2,-1,0},{-1,0,1},{0,1,2}};
    int secondarray[][] = {{-4,-3,-2},{-3,-2,-1},{-2,-1,0}};
    System.out.print ("First array has"+count_neg(firstarray));
    System.out.println("negative numbers");
    System.out.print ("Second array has"+count_neg(secondarray));
    System.out.println("negative numbers");
}

public static int count_neg(int x[][]){
    int count = 0;
    int i = 0; //rows
    int j = x.length - 1; //columns

    System.out.println("max column index is: "+j);
    while ( i >=0 && j<x.length){
        if (x[i][j] < 0){ // negative number
            count += (j + 1);// since j is an index...so j + 1
            i += 1;
        }
        else { // positive number
            j -= 1;
        }
    }
    return (count);
    }
}

我得到这个输出

max column index is: 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at O_n.count_neg(O_n.java:22)
    at O_n.main(O_n.java:9)
/home/eos/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java 
returned: 1
BUILD FAILED (total time: 0 seconds)

这段代码有什么问题?同样的事情在 python 中工作...

def count_neg(array):
    count = 0
    i = 0 # row
    j = len(array) -1 # col
    # since we are starting from right side

    while j >= 0 and i < len(array):
        if array[i][j] < 0: 
            count += (j + 1)
            i += 1
        else:
            j -= 1
    return count
print(count_neg([[-4,-3,-1,1],[-2,-2,1,2],[-1,1,2,3],[1,2,4,5]]))

最佳答案

我会这样写方法,只要遍历二维数组并在每次找到负数时增加count

public static int count_neg(int x[][]){
    int count = 0;

    for(int i = 0; i < x.length; i++){
        for(int j = 0; j < x[i].length; j++){
            if(x[i][j] < 0){
                count++;
            }
        }
    }
    return (count);
}

关于java - 计算数组中的负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50662932/

相关文章:

java - Wicket:更新 DropDownChoice 项目选择事件的模型

javascript - 使用 jQuery 访问 Google map PHP 中的数据

c++ - (C++) 试图完成一个快速程序,但我不确定哪里出错了?

c++ - 初始化结构的二维数组

c - C 中释放三维数组时的 SIGTRAP

c++ - 初始化一个未知维度的数组

java - 面向对象的设计——当一个类中有很多数据字段时,封装有多重要?

java - Servlet 映射限制图像可见

java - 为什么我的 ListView 仅在单击其文本时才响应?

javascript - 在 javascript 对象定义中连接字符串