2014-10-05 34 views
2

我想複製一個數組沒有指定的元素。比方說,我有以下陣列:複製數組沒有指定的元素java

int[] array = {1,2,3,4,5,6,7,8,9}; 
int[] array2 = new int[array.length-1]; 

我要的是複製數組不包含的int元素數組2「6」,所以它將包含 「{1,2,3,4,5, 7,8,9}」

我只是想用for循環,這是我到目前爲止,但它不工作

int[] array= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 
    int[] array2= new int[array.length - 1]; 
    int remove = 6; 
    for (int i = 0; i < array2.length; i++) { 
     if (array[i] != remove) { 
      array2[i] = array[i]; 
     } else { 
      array2[i] = array[i + 1]; 
      i++; 
     } 
    } 
    for (int i = 0; i < array2.length; i++) { 
     System.out.println(array2[i]); 
    } 

感謝

+0

什麼是「tab」和「tab2」?和「但它不工作」不是一個錯誤信息的好替代品。 – Tom 2014-10-05 21:58:11

+0

我的不好,選項卡是數組,而tab2是數組2 – 2014-10-05 22:02:30

+0

什麼不工作?你有錯誤嗎?另一個結果?什麼都沒有? – 2014-10-05 22:07:32

回答

4
int j = 0; 
int count = 0; //Set this variable to the number of times the 'remove' item appears in the list 
int[] array2 = new int[array.length - count]; 
int remove = 6; 
for(int i=0; i < array.length; i++) 
{ 
    if(array[i] != remove) 
     array2[j++] = array[i]; 
} 
+0

謝謝但array2的最後一個元素沒有被複制,出現0而不是9 – 2014-10-05 22:09:05

+0

@BobJ我猜你忘了把'int count = 0;'改成'int count = 1;'? – Tom 2014-10-05 22:10:21

+0

不能將array.length2而不是array.length。謝謝你的工作 – 2014-10-05 22:13:01

1

您也可以使用Java 8的流和lambda表達式來執行此操作:

int[] array= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 
int[] array2 = Arrays.stream(array).filter(value -> value != 6).toArray(); 
System.out.println(Arrays.toString(array2)); 
// Outputs: [1, 2, 3, 4, 5, 7, 8, 9]