2016-04-04 39 views
1

我必須創建一個方法,通過創建一個新數組來複制和打印數組中的偶數。我已經創建了一個名爲myNumbers的數組。我認爲問題在於myEvenNumbers[z]不會在myEvenNumbers[0]處存儲偶數,而是它會存儲第一個偶數在第一個索引myNumbers處的任何值。任何幫助將非常感激!如何創建只有偶數的數組副本?

這是我的代碼到目前爲止。

public static void copyAndPrintEvenNumbers() { 
    System.out.println("All the even numbers are: "); 
    int count = 0; 

    for (int i =0; i < myNumbers.length; i++) { 
     if (myNumbers[i] % 2 == 0) { 
      count++; 
     } 
     int[] myEvenNumbers = new int[count]; 
     for (int z = 0; z < myNumbers.length; z++) { 
      if (myNumbers[z] % 2 ==0) { 
       myEvenNumbers[z] = myNumbers[z]; 
       System.out.println(myEvenNumbers[z]); 
      } 
     } 

    } 

} 
+0

Java,我的錯。 – acho818

回答

1

您必須爲myEvenNumbers數組聲明第二個索引。當z超過myEvenNumbers數組的元素總數時,您將得到一個IndexOutOfBounds。還像Connor說的那樣,這兩個循環不應該嵌套。否則,您將丟棄前面的數組實例(myEvenNumbers)並導致內存泄漏。

public static void copyAndPrintEvenNumbers() { 

    System.out.println("All the even numbers are: "); 
    int count = 0; 

    for (int i =0; i < myNumbers.length; i++) { 
     if (myNumbers[i] % 2 == 0) { 
      count++; 
     } 
    } 

    int[] myEvenNumbers = new int[count]; 
    int myEvenIndex = 0; 
    for (int z = 0; z < myNumbers.length; z++) { 
     if (myNumbers[z] % 2 ==0) { 
      myEvenNumbers[myEvenIndex] = myNumbers[z]; 
      System.out.println(myEvenNumbers[myEvenIndex]); 
      myEvenIndex++; 
     } 
    } 

} 

個人而言,我會選擇偶數陣列相同的大小(內存小的開銷),以消除在第一循環中,因爲偶數的數量不能超過原始數組的計數。

public static void copyAndPrintEvenNumbers() { 

    System.out.println("All the even numbers are: "); 
    int count = 0; 

    int[] myEvenNumbers = new int[myNumbers.length]; 
    int count = 0; 
    for (int z = 0; z < myNumbers.length; z++) { 
     if (myNumbers[z] % 2 ==0) { 
      myEvenNumbers[count] = myNumbers[z]; 
      System.out.println(myEvenNumbers[count]); 
      count++; 
     } 
    } 
    System.out.println("There are " + count + " even numbers found"); 
} 
+0

這幫了很多。非常感謝你! – acho818

0

沒有必要讓你的第二個循環在第一個循環內。試試這個:

public static void copyAndPrintEvenNumbers() { 
    System.out.println("All the even numbers are: "); 
    int count = 0; 

    for (int i =0; i < myNumbers.length; i++) { 
     if (myNumbers[i] % 2 == 0) { 
      count++; 
     } 
    } 

    int[] myEvenNumbers = new int[count]; 
    int index = 0; 
    for(int i = 0; i < myNumbers.length; i++) { 
     if (myNumbers[i] % 2 ==0) { 
      myEvenNumbers[index] = myNumbers[i]; 
      index++; 
     } 
    } 
    System.out.println(myEvenNumbers); 
} 
+0

謝謝!我沒有意識到我的循環是嵌套的。 – acho818