【发布时间】:2012-09-22 08:24:17
【问题描述】:
我正在寻找在数组中找到负数的解决方案,我从搜索中想出了类似这样的代码。
public static void main(String args[]){
int arrayNumbers[] = { 3, 4, 7, -3, -2};
for (int i = 0; i <= arrayNumbers.length; i++){
int negativeCount = 0;
if (arrayNumbers[i] >= 0){
negativeCount++;
}
System.out.println(negativeCount);
}
}
我想知道与上面的代码相比,在数组中查找负数是否有更简单或更短的方法?
【问题讨论】:
-
计算的是
>= 0,而不是负数。 -
由于
for中的终止条件,该代码将生成越界异常。 -
该代码根本无法编译,您无法在 for 循环之外访问negativeCount。
-
@hmjd 所以有一个更短的方法。 ;)
-
你必须把
int negativeCount = 0;放在循环之前。否则计数器将在每次迭代时初始化为0
标签: java negative-number