首页 / JAVA / java – 计算数组中的负数
java – 计算数组中的负数
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 计算数组中的负数,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1888字,纯文字阅读大概需要3分钟。
内容图文
![java – 计算数组中的负数](/upload/InfoBanner/zyjiaocheng/797/d5d595cc45a84fdbb0070d7497fec848.jpg)
我试图在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<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]]))
解决方法:
您的索引与python版本相反:
while j >= 0 and i < len(array)
到Java版本:
while (i >= 0 && j < x.length)
// Change to
while (j >= 0 && i < x.length)
输出:
max column index is: 2
3
如果您使用的是Java8,则可以使用流来实现count_neg:
public static int countNeg(int x[][]) {
long count = Stream.of(x)
.flatMapToInt(arr -> IntStream.of(arr))
.filter(i -> i < 0)
.count();
return Math.toIntExact(count);
}
内容总结
以上是互联网集市为您收集整理的java – 计算数组中的负数全部内容,希望文章能够帮你解决java – 计算数组中的负数所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。