java数组为负数_java - 计算数组中的负数 - 堆栈内存溢出

我试图在2d阵列(square-matix)中找到负数的计数。 在矩阵中,如果你从上到下,左边写入数字增加。 这里的逻辑是从最后一列开始,然后继续向左。 如果找到neg num,则增加行索引并以相同的方式继续直到最后一行。 我在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

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]]))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值