【问题标题】:Compute the negative numbers in an array计算数组中的负数
【发布时间】: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);
    }
}

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

【问题讨论】:

  • 计算的是&gt;= 0,而不是负数。
  • 由于for 中的终止条件,该代码将生成越界异常。
  • 该代码根本无法编译,您无法在 for 循环之外访问negativeCount。
  • @hmjd 所以有一个更短的方法。 ;)
  • 你必须把int negativeCount = 0;放在循环之前。否则计数器将在每次迭代时初始化为0

标签: java negative-number


【解决方案1】:

代码的一些问题:

  • for 中的终止条件将产生越界异常(数组使用从零开始的索引)
  • negativeCount 的范围仅在for 之内
  • 否定检查不正确

稍短的版本将使用扩展的for

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

对于较短的版本(但可以说可读性较差),请消除 for{}

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

【讨论】:

  • 不加这行代码还能用吗-->这行代码-->int[] array = { 3, 4, 7, -3, -2};不明白它是如何初始化数组元素的
  • @PHZEOXIDE,我只是没有将它添加到 sn-ps,它是必需的。
【解决方案2】:

您的negativeCount 应该在您的循环之外声明。此外,您可以将您的System.out.println(negativeCount) 移到您的循环之外,因为它会在每次迭代时打印出来。。

你可以使用enhanced-for循环

public static void main(String args[]){
    int arrayNumbers[] = { 3, 4, 7, -3, -2};

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

    }
    System.out.println(negativeCount);
}

【讨论】:

  • 这里没有理由使用Integerint 适用于数组
  • 这更有意义,您能解释一下 for each 循环与 java 中的常规 for 循环有何不同吗?谢谢
  • @PHZEOXIDE.. 你可以通过JLS - enhanced for-loop
【解决方案3】:

使用 foreach 语法稍微短一点:

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

【讨论】:

  • 不加这行代码还能用吗-->这行代码-->int[] array = { 3, 4, 7, -3, -2};不明白它是如何初始化数组元素的。
  • @PHZEOXIDE 你必须添加行来初始化数组和打印负数的行,我的代码只做计数。
【解决方案4】:

一个基于 java 7 字符串的单行,计算减号:

System.out.println(Arrays.toString(array).replaceAll("[^-]+", "").length());

一种基于 Java 8 流的方式:

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

关于您的代码,它有一些问题:

  • 由于您不关心元素的索引,请改用foreach syntax
  • 在循环之外声明计数变量的范围,否则
    • 每次迭代都会一直设置为零,并且
    • 即使它包含正确的计数,您也无法使用它,因为它超出了您需要返回它的范围(仅在循环内部)(循环之后)
  • 使用正确的测试number &lt; 0(您的代码&gt;= 0计数负数)

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 2016-07-05
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    相关资源
    最近更新 更多