Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 计算数组中的负数_Java_Negative Number - Fatal编程技术网

Java 计算数组中的负数

Java 计算数组中的负数,java,negative-number,Java,Negative Number,我正在寻找在数组中查找负数的解决方案,我从搜索中得到了类似这样的代码 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){

我正在寻找在数组中查找负数的解决方案,我从搜索中得到了类似这样的代码

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);
    }
}

我想知道与上面的代码相比,是否有更简单或更短的方法来查找数组中的负数?

代码中的一些问题:

for中的终止条件将产生一个越界异常数组使用基于零的索引 negativeCount的范围仅在for的范围内 阴性检查不正确 稍短一点的版本将使用扩展的:


您的negativeCount应该在循环之外声明。。此外,您还可以将System.out.PrintLNegativeCount移到循环之外,因为它将为每次迭代打印

您可以使用增强的for循环


使用foreach语法稍微短一点:

 int negativeCount = 0;
 for(int i : arrayNumbers)
 {
      if(i < 0)negativeCount++;
 }

基于java 7字符串的一行程序,用于计算减号:

System.out.println(Arrays.toString(array).replaceAll("[^-]+", "").length());
基于Java 8流的方式:

System.out.println(Arrays.stream(array).filter(i -> i < 0).count());

这是计算>=0,而不是负数。由于for中的终止条件,该代码将生成一个越界异常。该代码根本不会编译,您无法在for循环之外访问negativeCount。@hmjd因此有一个较短的方法;你必须把int negativeCount=0;在循环之前。否则每次迭代计数器都会被初始化为0这里没有理由使用Integer,int与ArrayStat一起工作这更有意义你能解释for-each循环与java中常规for循环的不同吗?thanks@PHZEOXIDE.. 你可以在不添加->这行代码->int[]array={3,4,7,-3,-2}的情况下检查这段代码是否仍然有效;不了解如何初始化数组元素。@PHZEOXIDE您必须添加行以初始化数组,添加行以打印否定计数,我的代码只进行计数。如果不添加->这行代码->int[]数组={3,4,7,-3,-2},此代码是否仍然有效;不了解如何初始化数组elements@PHZEOXIDE,我只是没有将它添加到代码段中,它是必需的。
 int negativeCount = 0;
 for(int i : arrayNumbers)
 {
      if(i < 0)negativeCount++;
 }
System.out.println(Arrays.toString(array).replaceAll("[^-]+", "").length());
System.out.println(Arrays.stream(array).filter(i -> i < 0).count());
public static void main(String args[]) {
    int[] array = { 3, 4, 7, -3, -2};
    int negativeCount = 0;
    for (int number : array) {
        if (number < 0) {
            negativeCount++;
        }
    }
    System.out.println(negativeCount);
}