2012-10-01 36 views
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); 
    } 
} 

我想知道是否有更容易或更短的方式來找到數組中的負數與上面的代碼?

+8

這是計數'> = 0',而不是負數。 – assylias

+4

由於'for'中的終止條件,該代碼將生成越界異常。 – hmjd

+4

該代碼根本無法編譯,您無法訪問for循環之外的negativeCount。 – josefx

回答

2

與代碼的幾個問題:

  • 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++; 
+0

這段代碼是否仍然可以不加 - >這行代碼 - > int [] array = {3,4,7,-3,-2};不理解如何初始化數組元素 –

+0

@PHZEOXIDE,我只是沒有添加到片段,它是必需的。 – hmjd

0

你negativeCount應你的循環之外聲明..此外,您還可以將您的System.out.println(negativeCount)在循環之外,因爲它會在每次迭代時打印。

你也可以使用增強,爲循環

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

這裏沒有理由在這裏使用'Integer','int'可以和數組一起工作 – josefx

+0

這樣可以解釋爲什麼每個循環與java中的常規for循環不同?謝謝 –

+0

@PHZEOXIDE ..你可以通過[JLS - 增強的for-loop](http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.14.2 ) –

0

用的foreach語法更短一些:

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

這段代碼是否完全一樣? –

+0

這段代碼是否仍然工作,但不添加 - >這行代碼 - > int [] array = {3,4,7,-3,-2}; 不瞭解它如何初始化數組元素。 –

+0

@PHZEOXIDE你必須添加行來初始化數組和行來打印negativeCount,我的代碼只能進行計數。 – josefx

6

一個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 < 0(代碼>= 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); 
}